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