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