]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/places/placesitemmodel.cpp
Merge branch '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 Accessed" 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 // Only directories are allowed
440 continue;
441 }
442
443 PlacesItem* newItem = createPlacesItem(text, url);
444 const int dropIndex = groupedDropIndex(index, newItem);
445 insertItem(dropIndex, newItem);
446 }
447 }
448 }
449
450 KUrl PlacesItemModel::convertedUrl(const KUrl& url)
451 {
452 KUrl newUrl = url;
453 if (url.protocol() == QLatin1String("timeline")) {
454 newUrl = createTimelineUrl(url);
455 } else if (url.protocol() == QLatin1String("search")) {
456 newUrl = createSearchUrl(url);
457 }
458
459 return newUrl;
460 }
461
462 void PlacesItemModel::onItemInserted(int index)
463 {
464 const PlacesItem* insertedItem = placesItem(index);
465 if (insertedItem) {
466 // Take care to apply the PlacesItemModel-order of the inserted item
467 // also to the bookmark-manager.
468 const KBookmark insertedBookmark = insertedItem->bookmark();
469
470 const PlacesItem* previousItem = placesItem(index - 1);
471 KBookmark previousBookmark;
472 if (previousItem) {
473 previousBookmark = previousItem->bookmark();
474 }
475
476 m_bookmarkManager->root().moveBookmark(insertedBookmark, previousBookmark);
477 }
478
479 if (index == count() - 1) {
480 // The item has been appended as last item to the list. In this
481 // case assure that it is also appended after the hidden items and
482 // not before (like done otherwise).
483 m_bookmarkedItems.append(0);
484 } else {
485
486 int modelIndex = -1;
487 int bookmarkIndex = 0;
488 while (bookmarkIndex < m_bookmarkedItems.count()) {
489 if (!m_bookmarkedItems[bookmarkIndex]) {
490 ++modelIndex;
491 if (modelIndex + 1 == index) {
492 break;
493 }
494 }
495 ++bookmarkIndex;
496 }
497 m_bookmarkedItems.insert(bookmarkIndex, 0);
498 }
499
500 triggerBookmarksSaving();
501
502 #ifdef PLACESITEMMODEL_DEBUG
503 kDebug() << "Inserted item" << index;
504 showModelState();
505 #endif
506 }
507
508 void PlacesItemModel::onItemRemoved(int index, KStandardItem* removedItem)
509 {
510 PlacesItem* placesItem = dynamic_cast<PlacesItem*>(removedItem);
511 if (placesItem) {
512 const KBookmark bookmark = placesItem->bookmark();
513 m_bookmarkManager->root().deleteBookmark(bookmark);
514 }
515
516 const int boomarkIndex = bookmarkIndex(index);
517 Q_ASSERT(!m_bookmarkedItems[boomarkIndex]);
518 m_bookmarkedItems.removeAt(boomarkIndex);
519
520 triggerBookmarksSaving();
521
522 #ifdef PLACESITEMMODEL_DEBUG
523 kDebug() << "Removed item" << index;
524 showModelState();
525 #endif
526 }
527
528 void PlacesItemModel::onItemChanged(int index, const QSet<QByteArray>& changedRoles)
529 {
530 const PlacesItem* changedItem = placesItem(index);
531 if (changedItem) {
532 // Take care to apply the PlacesItemModel-order of the changed item
533 // also to the bookmark-manager.
534 const KBookmark insertedBookmark = changedItem->bookmark();
535
536 const PlacesItem* previousItem = placesItem(index - 1);
537 KBookmark previousBookmark;
538 if (previousItem) {
539 previousBookmark = previousItem->bookmark();
540 }
541
542 m_bookmarkManager->root().moveBookmark(insertedBookmark, previousBookmark);
543 }
544
545 if (changedRoles.contains("isHidden")) {
546 if (!m_hiddenItemsShown && changedItem->isHidden()) {
547 m_hiddenItemToRemove = index;
548 QTimer::singleShot(0, this, SLOT(hideItem()));
549 }
550 }
551
552 triggerBookmarksSaving();
553 }
554
555 void PlacesItemModel::slotDeviceAdded(const QString& udi)
556 {
557 const Solid::Device device(udi);
558
559 if (!m_predicate.matches(device)) {
560 return;
561 }
562
563 m_availableDevices << udi;
564 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
565 appendItem(new PlacesItem(bookmark));
566 }
567
568 void PlacesItemModel::slotDeviceRemoved(const QString& udi)
569 {
570 if (!m_availableDevices.contains(udi)) {
571 return;
572 }
573
574 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
575 PlacesItem* item = m_bookmarkedItems[i];
576 if (item && item->udi() == udi) {
577 m_bookmarkedItems.removeAt(i);
578 delete item;
579 return;
580 }
581 }
582
583 for (int i = 0; i < count(); ++i) {
584 if (placesItem(i)->udi() == udi) {
585 removeItem(i);
586 return;
587 }
588 }
589 }
590
591 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error, const QVariant& errorData)
592 {
593 if (error && errorData.isValid()) {
594 emit errorMessage(errorData.toString());
595 }
596 }
597
598 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error,
599 const QVariant& errorData,
600 const QString& udi)
601 {
602 Q_UNUSED(udi);
603
604 Q_ASSERT(!m_storageSetupInProgress.isEmpty());
605 const int index = m_storageSetupInProgress.take(sender());
606 const PlacesItem* item = placesItem(index);
607 if (!item) {
608 return;
609 }
610
611 if (error) {
612 if (errorData.isValid()) {
613 emit errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
614 item->text(),
615 errorData.toString()));
616 } else {
617 emit errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
618 item->text()));
619 }
620 emit storageSetupDone(index, false);
621 } else {
622 emit storageSetupDone(index, true);
623 }
624 }
625
626 void PlacesItemModel::hideItem()
627 {
628 hideItem(m_hiddenItemToRemove);
629 m_hiddenItemToRemove = -1;
630 }
631
632 void PlacesItemModel::updateBookmarks()
633 {
634 // Verify whether new bookmarks have been added or existing
635 // bookmarks have been changed.
636 KBookmarkGroup root = m_bookmarkManager->root();
637 KBookmark newBookmark = root.first();
638 while (!newBookmark.isNull()) {
639 if (acceptBookmark(newBookmark, m_availableDevices)) {
640 bool found = false;
641 int modelIndex = 0;
642 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
643 PlacesItem* item = m_bookmarkedItems[i];
644 if (!item) {
645 item = placesItem(modelIndex);
646 ++modelIndex;
647 }
648
649 const KBookmark oldBookmark = item->bookmark();
650 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
651 // The bookmark has been found in the model or as
652 // a hidden item. The content of the bookmark might
653 // have been changed, so an update is done.
654 found = true;
655 if (newBookmark.metaDataItem("UDI").isEmpty()) {
656 item->setBookmark(newBookmark);
657 item->setText(i18nc("KFile System Bookmarks", newBookmark.text().toUtf8().data()));
658 }
659 break;
660 }
661 }
662
663 if (!found) {
664 const QString udi = newBookmark.metaDataItem("UDI");
665
666 /*
667 * See Bug 304878
668 * Only add a new places item, if the item text is not empty
669 * and if the device is available. Fixes the strange behaviour -
670 * add a places item without text in the Places section - when you
671 * remove a device (e.g. a usb stick) without unmounting.
672 */
673 if (udi.isEmpty() || Solid::Device(udi).isValid()) {
674 PlacesItem* item = new PlacesItem(newBookmark);
675 if (item->isHidden() && !m_hiddenItemsShown) {
676 m_bookmarkedItems.append(item);
677 } else {
678 appendItemToGroup(item);
679 }
680 }
681 }
682 }
683
684 newBookmark = root.next(newBookmark);
685 }
686
687 // Remove items that are not part of the bookmark-manager anymore
688 int modelIndex = 0;
689 for (int i = m_bookmarkedItems.count() - 1; i >= 0; --i) {
690 PlacesItem* item = m_bookmarkedItems[i];
691 const bool itemIsPartOfModel = (item == 0);
692 if (itemIsPartOfModel) {
693 item = placesItem(modelIndex);
694 }
695
696 bool hasBeenRemoved = true;
697 const KBookmark oldBookmark = item->bookmark();
698 KBookmark newBookmark = root.first();
699 while (!newBookmark.isNull()) {
700 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
701 hasBeenRemoved = false;
702 break;
703 }
704 newBookmark = root.next(newBookmark);
705 }
706
707 if (hasBeenRemoved) {
708 if (m_bookmarkedItems[i]) {
709 delete m_bookmarkedItems[i];
710 m_bookmarkedItems.removeAt(i);
711 } else {
712 removeItem(modelIndex);
713 --modelIndex;
714 }
715 }
716
717 if (itemIsPartOfModel) {
718 ++modelIndex;
719 }
720 }
721 }
722
723 void PlacesItemModel::saveBookmarks()
724 {
725 m_bookmarkManager->emitChanged(m_bookmarkManager->root());
726 }
727
728 void PlacesItemModel::loadBookmarks()
729 {
730 KBookmarkGroup root = m_bookmarkManager->root();
731 KBookmark bookmark = root.first();
732 QSet<QString> devices = m_availableDevices;
733
734 QSet<KUrl> missingSystemBookmarks;
735 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
736 missingSystemBookmarks.insert(data.url);
737 }
738
739 // The bookmarks might have a mixed order of places, devices and search-groups due
740 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
741 // items should always be collected in one group so the items are collected first
742 // in separate lists before inserting them.
743 QList<PlacesItem*> placesItems;
744 QList<PlacesItem*> recentlyAccessedItems;
745 QList<PlacesItem*> searchForItems;
746 QList<PlacesItem*> devicesItems;
747
748 while (!bookmark.isNull()) {
749 if (acceptBookmark(bookmark, devices)) {
750 PlacesItem* item = new PlacesItem(bookmark);
751 if (item->groupType() == PlacesItem::DevicesType) {
752 devices.remove(item->udi());
753 devicesItems.append(item);
754 } else {
755 const KUrl url = bookmark.url();
756 if (missingSystemBookmarks.contains(url)) {
757 missingSystemBookmarks.remove(url);
758
759 // Try to retranslate the text of system bookmarks to have translated
760 // items when changing the language. In case if the user has applied a custom
761 // text, the retranslation will fail and the users custom text is still used.
762 // It is important to use "KFile System Bookmarks" as context (see
763 // createSystemBookmarks()).
764 item->setText(i18nc("KFile System Bookmarks", bookmark.text().toUtf8().data()));
765 item->setSystemItem(true);
766 }
767
768 switch (item->groupType()) {
769 case PlacesItem::PlacesType: placesItems.append(item); break;
770 case PlacesItem::RecentlyAccessedType: recentlyAccessedItems.append(item); break;
771 case PlacesItem::SearchForType: searchForItems.append(item); break;
772 case PlacesItem::DevicesType:
773 default: Q_ASSERT(false); break;
774 }
775 }
776 }
777
778 bookmark = root.next(bookmark);
779 }
780
781 if (!missingSystemBookmarks.isEmpty()) {
782 // The current bookmarks don't contain all system-bookmarks. Add the missing
783 // bookmarks.
784 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
785 if (missingSystemBookmarks.contains(data.url)) {
786 PlacesItem* item = createSystemPlacesItem(data);
787 switch (item->groupType()) {
788 case PlacesItem::PlacesType: placesItems.append(item); break;
789 case PlacesItem::RecentlyAccessedType: recentlyAccessedItems.append(item); break;
790 case PlacesItem::SearchForType: searchForItems.append(item); break;
791 case PlacesItem::DevicesType:
792 default: Q_ASSERT(false); break;
793 }
794 }
795 }
796 }
797
798 // Create items for devices that have not been stored as bookmark yet
799 foreach (const QString& udi, devices) {
800 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
801 devicesItems.append(new PlacesItem(bookmark));
802 }
803
804 QList<PlacesItem*> items;
805 items.append(placesItems);
806 items.append(recentlyAccessedItems);
807 items.append(searchForItems);
808 items.append(devicesItems);
809
810 foreach (PlacesItem* item, items) {
811 if (!m_hiddenItemsShown && item->isHidden()) {
812 m_bookmarkedItems.append(item);
813 } else {
814 appendItem(item);
815 }
816 }
817
818 #ifdef PLACESITEMMODEL_DEBUG
819 kDebug() << "Loaded bookmarks";
820 showModelState();
821 #endif
822 }
823
824 bool PlacesItemModel::acceptBookmark(const KBookmark& bookmark,
825 const QSet<QString>& availableDevices) const
826 {
827 const QString udi = bookmark.metaDataItem("UDI");
828 const KUrl url = bookmark.url();
829 const QString appName = bookmark.metaDataItem("OnlyInApp");
830 const bool deviceAvailable = availableDevices.contains(udi);
831
832 const bool allowedHere = (appName.isEmpty()
833 || appName == KGlobal::mainComponent().componentName()
834 || appName == KGlobal::mainComponent().componentName() + AppNamePrefix)
835 && (m_fileIndexingEnabled || (url.protocol() != QLatin1String("timeline") &&
836 url.protocol() != QLatin1String("search")));
837
838 return (udi.isEmpty() && allowedHere) || deviceAvailable;
839 }
840
841 PlacesItem* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData& data)
842 {
843 KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager,
844 data.text,
845 data.url,
846 data.icon);
847
848 const QString protocol = data.url.protocol();
849 if (protocol == QLatin1String("timeline") || protocol == QLatin1String("search")) {
850 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
851 // for "Recently Accessed" and "Search For" should be a setting available only
852 // in the Places Panel (see description of AppNamePrefix for more details).
853 const QString appName = KGlobal::mainComponent().componentName() + AppNamePrefix;
854 bookmark.setMetaDataItem("OnlyInApp", appName);
855 }
856
857 PlacesItem* item = new PlacesItem(bookmark);
858 item->setSystemItem(true);
859
860 // Create default view-properties for all "Search For" and "Recently Accessed" bookmarks
861 // in case if the user has not already created custom view-properties for a corresponding
862 // query yet.
863 const bool createDefaultViewProperties = (item->groupType() == PlacesItem::SearchForType ||
864 item->groupType() == PlacesItem::RecentlyAccessedType) &&
865 !GeneralSettings::self()->globalViewProps();
866 if (createDefaultViewProperties) {
867 ViewProperties props(convertedUrl(data.url));
868 if (!props.exist()) {
869 const QString path = data.url.path();
870 if (path == QLatin1String("/documents")) {
871 props.setViewMode(DolphinView::DetailsView);
872 props.setPreviewsShown(false);
873 props.setVisibleRoles(QList<QByteArray>() << "text" << "path");
874 } else if (path == QLatin1String("/images")) {
875 props.setViewMode(DolphinView::IconsView);
876 props.setPreviewsShown(true);
877 props.setVisibleRoles(QList<QByteArray>() << "text" << "imageSize");
878 } else if (path == QLatin1String("/audio")) {
879 props.setViewMode(DolphinView::DetailsView);
880 props.setPreviewsShown(false);
881 props.setVisibleRoles(QList<QByteArray>() << "text" << "artist" << "album");
882 } else if (path == QLatin1String("/videos")) {
883 props.setViewMode(DolphinView::IconsView);
884 props.setPreviewsShown(true);
885 props.setVisibleRoles(QList<QByteArray>() << "text");
886 } else if (data.url.protocol() == "timeline") {
887 props.setViewMode(DolphinView::DetailsView);
888 props.setVisibleRoles(QList<QByteArray>() << "text" << "date");
889 }
890 }
891 }
892
893 return item;
894 }
895
896 void PlacesItemModel::createSystemBookmarks()
897 {
898 Q_ASSERT(m_systemBookmarks.isEmpty());
899 Q_ASSERT(m_systemBookmarksIndexes.isEmpty());
900
901 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
902 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
903 // done here is because otherwise switching the language would not result in retranslating the
904 // bookmarks.
905 m_systemBookmarks.append(SystemBookmarkData(KUrl(KUser().homeDir()),
906 "user-home",
907 I18N_NOOP2("KFile System Bookmarks", "Home")));
908 m_systemBookmarks.append(SystemBookmarkData(KUrl("remote:/"),
909 "network-workgroup",
910 I18N_NOOP2("KFile System Bookmarks", "Network")));
911 m_systemBookmarks.append(SystemBookmarkData(KUrl("/"),
912 "folder-red",
913 I18N_NOOP2("KFile System Bookmarks", "Root")));
914 m_systemBookmarks.append(SystemBookmarkData(KUrl("trash:/"),
915 "user-trash",
916 I18N_NOOP2("KFile System Bookmarks", "Trash")));
917
918 if (m_fileIndexingEnabled) {
919 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/today"),
920 "go-jump-today",
921 I18N_NOOP2("KFile System Bookmarks", "Today")));
922 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/yesterday"),
923 "view-calendar-day",
924 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
925 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/thismonth"),
926 "view-calendar-month",
927 I18N_NOOP2("KFile System Bookmarks", "This Month")));
928 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/lastmonth"),
929 "view-calendar-month",
930 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
931 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/documents"),
932 "folder-txt",
933 I18N_NOOP2("KFile System Bookmarks", "Documents")));
934 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/images"),
935 "folder-image",
936 I18N_NOOP2("KFile System Bookmarks", "Images")));
937 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/audio"),
938 "folder-sound",
939 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
940 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/videos"),
941 "folder-video",
942 I18N_NOOP2("KFile System Bookmarks", "Videos")));
943 }
944
945 for (int i = 0; i < m_systemBookmarks.count(); ++i) {
946 m_systemBookmarksIndexes.insert(m_systemBookmarks[i].url, i);
947 }
948 }
949
950 void PlacesItemModel::clear() {
951 m_bookmarkedItems.clear();
952 KStandardItemModel::clear();
953 }
954
955 void PlacesItemModel::initializeAvailableDevices()
956 {
957 QString predicate("[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
958 " OR "
959 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
960 " OR "
961 "OpticalDisc.availableContent & 'Audio' ]"
962 " OR "
963 "StorageAccess.ignored == false ]");
964
965
966 if (KProtocolInfo::isKnownProtocol("mtp")) {
967 predicate.prepend("[");
968 predicate.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']");
969 }
970
971 m_predicate = Solid::Predicate::fromString(predicate);
972 Q_ASSERT(m_predicate.isValid());
973
974 Solid::DeviceNotifier* notifier = Solid::DeviceNotifier::instance();
975 connect(notifier, SIGNAL(deviceAdded(QString)), this, SLOT(slotDeviceAdded(QString)));
976 connect(notifier, SIGNAL(deviceRemoved(QString)), this, SLOT(slotDeviceRemoved(QString)));
977
978 const QList<Solid::Device>& deviceList = Solid::Device::listFromQuery(m_predicate);
979 foreach (const Solid::Device& device, deviceList) {
980 m_availableDevices << device.udi();
981 }
982 }
983
984 int PlacesItemModel::bookmarkIndex(int index) const
985 {
986 int bookmarkIndex = 0;
987 int modelIndex = 0;
988 while (bookmarkIndex < m_bookmarkedItems.count()) {
989 if (!m_bookmarkedItems[bookmarkIndex]) {
990 if (modelIndex == index) {
991 break;
992 }
993 ++modelIndex;
994 }
995 ++bookmarkIndex;
996 }
997
998 return bookmarkIndex >= m_bookmarkedItems.count() ? -1 : bookmarkIndex;
999 }
1000
1001 void PlacesItemModel::hideItem(int index)
1002 {
1003 PlacesItem* shownItem = placesItem(index);
1004 if (!shownItem) {
1005 return;
1006 }
1007
1008 shownItem->setHidden(true);
1009 if (m_hiddenItemsShown) {
1010 // Removing items from the model is not allowed if all hidden
1011 // items should be shown.
1012 return;
1013 }
1014
1015 const int newIndex = bookmarkIndex(index);
1016 if (newIndex >= 0) {
1017 const KBookmark hiddenBookmark = shownItem->bookmark();
1018 PlacesItem* hiddenItem = new PlacesItem(hiddenBookmark);
1019
1020 const PlacesItem* previousItem = placesItem(index - 1);
1021 KBookmark previousBookmark;
1022 if (previousItem) {
1023 previousBookmark = previousItem->bookmark();
1024 }
1025
1026 const bool updateBookmark = (m_bookmarkManager->root().indexOf(hiddenBookmark) >= 0);
1027 removeItem(index);
1028
1029 if (updateBookmark) {
1030 // removeItem() also removed the bookmark from m_bookmarkManager in
1031 // PlacesItemModel::onItemRemoved(). However for hidden items the
1032 // bookmark should still be remembered, so readd it again:
1033 m_bookmarkManager->root().addBookmark(hiddenBookmark);
1034 m_bookmarkManager->root().moveBookmark(hiddenBookmark, previousBookmark);
1035 triggerBookmarksSaving();
1036 }
1037
1038 m_bookmarkedItems.insert(newIndex, hiddenItem);
1039 }
1040 }
1041
1042 void PlacesItemModel::triggerBookmarksSaving()
1043 {
1044 if (m_saveBookmarksTimer) {
1045 m_saveBookmarksTimer->start();
1046 }
1047 }
1048
1049 QString PlacesItemModel::internalMimeType() const
1050 {
1051 return "application/x-dolphinplacesmodel-" +
1052 QString::number((qptrdiff)this);
1053 }
1054
1055 int PlacesItemModel::groupedDropIndex(int index, const PlacesItem* item) const
1056 {
1057 Q_ASSERT(item);
1058
1059 int dropIndex = index;
1060 const PlacesItem::GroupType type = item->groupType();
1061
1062 const int itemCount = count();
1063 if (index < 0) {
1064 dropIndex = itemCount;
1065 }
1066
1067 // Search nearest previous item with the same group
1068 int previousIndex = -1;
1069 for (int i = dropIndex - 1; i >= 0; --i) {
1070 if (placesItem(i)->groupType() == type) {
1071 previousIndex = i;
1072 break;
1073 }
1074 }
1075
1076 // Search nearest next item with the same group
1077 int nextIndex = -1;
1078 for (int i = dropIndex; i < count(); ++i) {
1079 if (placesItem(i)->groupType() == type) {
1080 nextIndex = i;
1081 break;
1082 }
1083 }
1084
1085 // Adjust the drop-index to be inserted to the
1086 // nearest item with the same group.
1087 if (previousIndex >= 0 && nextIndex >= 0) {
1088 dropIndex = (dropIndex - previousIndex < nextIndex - dropIndex) ?
1089 previousIndex + 1 : nextIndex;
1090 } else if (previousIndex >= 0) {
1091 dropIndex = previousIndex + 1;
1092 } else if (nextIndex >= 0) {
1093 dropIndex = nextIndex;
1094 }
1095
1096 return dropIndex;
1097 }
1098
1099 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark& b1, const KBookmark& b2)
1100 {
1101 const QString udi1 = b1.metaDataItem("UDI");
1102 const QString udi2 = b2.metaDataItem("UDI");
1103 if (!udi1.isEmpty() && !udi2.isEmpty()) {
1104 return udi1 == udi2;
1105 } else {
1106 return b1.metaDataItem("ID") == b2.metaDataItem("ID");
1107 }
1108 }
1109
1110 KUrl PlacesItemModel::createTimelineUrl(const KUrl& url)
1111 {
1112 // TODO: Clarify with the Baloo-team whether it makes sense
1113 // provide default-timeline-URLs like 'yesterday', 'this month'
1114 // and 'last month'.
1115 KUrl timelineUrl;
1116
1117 const QString path = url.pathOrUrl();
1118 if (path.endsWith(QLatin1String("yesterday"))) {
1119 const QDate date = QDate::currentDate().addDays(-1);
1120 const int year = date.year();
1121 const int month = date.month();
1122 const int day = date.day();
1123 timelineUrl = "timeline:/" + timelineDateString(year, month) +
1124 '/' + timelineDateString(year, month, day);
1125 } else if (path.endsWith(QLatin1String("thismonth"))) {
1126 const QDate date = QDate::currentDate();
1127 timelineUrl = "timeline:/" + timelineDateString(date.year(), date.month());
1128 } else if (path.endsWith(QLatin1String("lastmonth"))) {
1129 const QDate date = QDate::currentDate().addMonths(-1);
1130 timelineUrl = "timeline:/" + timelineDateString(date.year(), date.month());
1131 } else {
1132 Q_ASSERT(path.endsWith(QLatin1String("today")));
1133 timelineUrl= url;
1134 }
1135
1136 return timelineUrl;
1137 }
1138
1139 QString PlacesItemModel::timelineDateString(int year, int month, int day)
1140 {
1141 QString date = QString::number(year) + '-';
1142 if (month < 10) {
1143 date += '0';
1144 }
1145 date += QString::number(month);
1146
1147 if (day >= 1) {
1148 date += '-';
1149 if (day < 10) {
1150 date += '0';
1151 }
1152 date += QString::number(day);
1153 }
1154
1155 return date;
1156 }
1157
1158 KUrl PlacesItemModel::createSearchUrl(const KUrl& url)
1159 {
1160 KUrl searchUrl;
1161
1162 #ifdef HAVE_BALOO
1163 const QString path = url.pathOrUrl();
1164 if (path.endsWith(QLatin1String("documents"))) {
1165 searchUrl = searchUrlForType("Document");
1166 } else if (path.endsWith(QLatin1String("images"))) {
1167 searchUrl = searchUrlForType("Image");
1168 } else if (path.endsWith(QLatin1String("audio"))) {
1169 searchUrl = searchUrlForType("Audio");
1170 } else if (path.endsWith(QLatin1String("videos"))) {
1171 searchUrl = searchUrlForType("Video");
1172 } else {
1173 Q_ASSERT(false);
1174 }
1175 #else
1176 Q_UNUSED(url);
1177 #endif
1178
1179 return searchUrl;
1180 }
1181
1182 #ifdef HAVE_BALOO
1183 KUrl PlacesItemModel::searchUrlForType(const QString& type)
1184 {
1185 Baloo::Query query;
1186 query.addType("File");
1187 query.addType(type);
1188
1189 return query.toSearchUrl();
1190 }
1191 #endif
1192
1193 #ifdef PLACESITEMMODEL_DEBUG
1194 void PlacesItemModel::showModelState()
1195 {
1196 kDebug() << "=================================";
1197 kDebug() << "Model:";
1198 kDebug() << "hidden-index model-index text";
1199 int modelIndex = 0;
1200 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
1201 if (m_bookmarkedItems[i]) {
1202 kDebug() << i << "(Hidden) " << " " << m_bookmarkedItems[i]->dataValue("text").toString();
1203 } else {
1204 if (item(modelIndex)) {
1205 kDebug() << i << " " << modelIndex << " " << item(modelIndex)->dataValue("text").toString();
1206 } else {
1207 kDebug() << i << " " << modelIndex << " " << "(not available yet)";
1208 }
1209 ++modelIndex;
1210 }
1211 }
1212
1213 kDebug();
1214 kDebug() << "Bookmarks:";
1215
1216 int bookmarkIndex = 0;
1217 KBookmarkGroup root = m_bookmarkManager->root();
1218 KBookmark bookmark = root.first();
1219 while (!bookmark.isNull()) {
1220 const QString udi = bookmark.metaDataItem("UDI");
1221 const QString text = udi.isEmpty() ? bookmark.text() : udi;
1222 if (bookmark.metaDataItem("IsHidden") == QLatin1String("true")) {
1223 kDebug() << bookmarkIndex << "(Hidden)" << text;
1224 } else {
1225 kDebug() << bookmarkIndex << " " << text;
1226 }
1227
1228 bookmark = root.next(bookmark);
1229 ++bookmarkIndex;
1230 }
1231 }
1232 #endif
1233
1234 #include "placesitemmodel.moc"