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