]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/places/placesitemmodel.cpp
Merge branch 'KDE/4.9'
[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_NEPOMUK
55 #include <Nepomuk2/ResourceManager>
56 #include <Nepomuk2/Query/ComparisonTerm>
57 #include <Nepomuk2/Query/LiteralTerm>
58 #include <Nepomuk2/Query/FileQuery>
59 #include <Nepomuk2/Query/ResourceTypeTerm>
60 #include <Nepomuk2/Vocabulary/NFO>
61 #include <Nepomuk2/Vocabulary/NIE>
62 #endif
63
64 namespace {
65 // As long as KFilePlacesView from kdelibs is available in parallel, the
66 // system-bookmarks for "Recently Accessed" and "Search For" should be
67 // shown only inside the Places Panel. This is necessary as the stored
68 // URLs needs to get translated to a Nepomuk-search-URL on-the-fly to
69 // be independent from changes in the Nepomuk-search-URL-syntax.
70 // Hence a prefix to the application-name of the stored bookmarks is
71 // added, which is only read by PlacesItemModel.
72 const char* AppNamePrefix = "-places-panel";
73 }
74
75 PlacesItemModel::PlacesItemModel(QObject* parent) :
76 KStandardItemModel(parent),
77 m_fileIndexingEnabled(false),
78 m_hiddenItemsShown(false),
79 m_availableDevices(),
80 m_predicate(),
81 m_bookmarkManager(0),
82 m_systemBookmarks(),
83 m_systemBookmarksIndexes(),
84 m_bookmarkedItems(),
85 m_hiddenItemToRemove(-1),
86 m_saveBookmarksTimer(0),
87 m_updateBookmarksTimer(0),
88 m_storageSetupInProgress()
89 {
90 #ifdef HAVE_NEPOMUK
91 if (Nepomuk2::ResourceManager::instance()->initialized()) {
92 KConfig config("nepomukserverrc");
93 m_fileIndexingEnabled = config.group("Service-nepomukfileindexer").readEntry("autostart", false);
94 }
95
96 #endif
97 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
98 m_bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
99
100 createSystemBookmarks();
101 initializeAvailableDevices();
102 loadBookmarks();
103
104 const int syncBookmarksTimeout = 100;
105
106 m_saveBookmarksTimer = new QTimer(this);
107 m_saveBookmarksTimer->setInterval(syncBookmarksTimeout);
108 m_saveBookmarksTimer->setSingleShot(true);
109 connect(m_saveBookmarksTimer, SIGNAL(timeout()), this, SLOT(saveBookmarks()));
110
111 m_updateBookmarksTimer = new QTimer(this);
112 m_updateBookmarksTimer->setInterval(syncBookmarksTimeout);
113 m_updateBookmarksTimer->setSingleShot(true);
114 connect(m_updateBookmarksTimer, SIGNAL(timeout()), this, SLOT(updateBookmarks()));
115
116 connect(m_bookmarkManager, SIGNAL(changed(QString,QString)),
117 m_updateBookmarksTimer, SLOT(start()));
118 connect(m_bookmarkManager, SIGNAL(bookmarksChanged(QString)),
119 m_updateBookmarksTimer, SLOT(start()));
120 }
121
122 PlacesItemModel::~PlacesItemModel()
123 {
124 saveBookmarks();
125 qDeleteAll(m_bookmarkedItems);
126 m_bookmarkedItems.clear();
127 }
128
129 PlacesItem* PlacesItemModel::createPlacesItem(const QString& text,
130 const KUrl& url,
131 const QString& iconName)
132 {
133 const KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager, text, url, iconName);
134 return new PlacesItem(bookmark);
135 }
136
137 PlacesItem* PlacesItemModel::placesItem(int index) const
138 {
139 return dynamic_cast<PlacesItem*>(item(index));
140 }
141
142 int PlacesItemModel::hiddenCount() const
143 {
144 int modelIndex = 0;
145 int hiddenItemCount = 0;
146 foreach (const PlacesItem* item, m_bookmarkedItems) {
147 if (item) {
148 ++hiddenItemCount;
149 } else {
150 if (placesItem(modelIndex)->isHidden()) {
151 ++hiddenItemCount;
152 }
153 ++modelIndex;
154 }
155 }
156
157 return hiddenItemCount;
158 }
159
160 void PlacesItemModel::setHiddenItemsShown(bool show)
161 {
162 if (m_hiddenItemsShown == show) {
163 return;
164 }
165
166 m_hiddenItemsShown = show;
167
168 if (show) {
169 // Move all items that are part of m_bookmarkedItems to the model.
170 QList<PlacesItem*> itemsToInsert;
171 QList<int> insertPos;
172 int modelIndex = 0;
173 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
174 if (m_bookmarkedItems[i]) {
175 itemsToInsert.append(m_bookmarkedItems[i]);
176 m_bookmarkedItems[i] = 0;
177 insertPos.append(modelIndex);
178 }
179 ++modelIndex;
180 }
181
182 // Inserting the items will automatically insert an item
183 // to m_bookmarkedItems in PlacesItemModel::onItemsInserted().
184 // The items are temporary saved in itemsToInsert, so
185 // m_bookmarkedItems can be shrinked now.
186 m_bookmarkedItems.erase(m_bookmarkedItems.begin(),
187 m_bookmarkedItems.begin() + itemsToInsert.count());
188
189 for (int i = 0; i < itemsToInsert.count(); ++i) {
190 insertItem(insertPos[i], itemsToInsert[i]);
191 }
192
193 Q_ASSERT(m_bookmarkedItems.count() == count());
194 } else {
195 // Move all items of the model, where the "isHidden" property is true, to
196 // m_bookmarkedItems.
197 Q_ASSERT(m_bookmarkedItems.count() == count());
198 for (int i = count() - 1; i >= 0; --i) {
199 if (placesItem(i)->isHidden()) {
200 hideItem(i);
201 }
202 }
203 }
204
205 #ifdef PLACESITEMMODEL_DEBUG
206 kDebug() << "Changed visibility of hidden items";
207 showModelState();
208 #endif
209 }
210
211 bool PlacesItemModel::hiddenItemsShown() const
212 {
213 return m_hiddenItemsShown;
214 }
215
216 int PlacesItemModel::closestItem(const KUrl& url) const
217 {
218 int foundIndex = -1;
219 int maxLength = 0;
220
221 for (int i = 0; i < count(); ++i) {
222 const KUrl itemUrl = placesItem(i)->url();
223 if (itemUrl.isParentOf(url)) {
224 const int length = itemUrl.prettyUrl().length();
225 if (length > maxLength) {
226 foundIndex = i;
227 maxLength = length;
228 }
229 }
230 }
231
232 return foundIndex;
233 }
234
235 void PlacesItemModel::appendItemToGroup(PlacesItem* item)
236 {
237 if (!item) {
238 return;
239 }
240
241 int i = 0;
242 while (i < count() && placesItem(i)->group() != item->group()) {
243 ++i;
244 }
245
246 bool inserted = false;
247 while (!inserted && i < count()) {
248 if (placesItem(i)->group() != item->group()) {
249 insertItem(i, item);
250 inserted = true;
251 }
252 ++i;
253 }
254
255 if (!inserted) {
256 appendItem(item);
257 }
258 }
259
260
261 QAction* PlacesItemModel::ejectAction(int index) const
262 {
263 const PlacesItem* item = placesItem(index);
264 if (item && item->device().is<Solid::OpticalDisc>()) {
265 return new QAction(KIcon("media-eject"), i18nc("@item", "Eject '%1'", item->text()), 0);
266 }
267
268 return 0;
269 }
270
271 QAction* PlacesItemModel::teardownAction(int index) const
272 {
273 const PlacesItem* item = placesItem(index);
274 if (!item) {
275 return 0;
276 }
277
278 Solid::Device device = item->device();
279 const bool providesTearDown = device.is<Solid::StorageAccess>() &&
280 device.as<Solid::StorageAccess>()->isAccessible();
281 if (!providesTearDown) {
282 return 0;
283 }
284
285 Solid::StorageDrive* drive = device.as<Solid::StorageDrive>();
286 if (!drive) {
287 drive = device.parent().as<Solid::StorageDrive>();
288 }
289
290 bool hotPluggable = false;
291 bool removable = false;
292 if (drive) {
293 hotPluggable = drive->isHotpluggable();
294 removable = drive->isRemovable();
295 }
296
297 QString iconName;
298 QString text;
299 const QString label = item->text();
300 if (device.is<Solid::OpticalDisc>()) {
301 text = i18nc("@item", "Release '%1'", label);
302 } else if (removable || hotPluggable) {
303 text = i18nc("@item", "Safely Remove '%1'", label);
304 iconName = "media-eject";
305 } else {
306 text = i18nc("@item", "Unmount '%1'", label);
307 iconName = "media-eject";
308 }
309
310 if (iconName.isEmpty()) {
311 return new QAction(text, 0);
312 }
313
314 return new QAction(KIcon(iconName), text, 0);
315 }
316
317 void PlacesItemModel::requestEject(int index)
318 {
319 const PlacesItem* item = placesItem(index);
320 if (item) {
321 Solid::OpticalDrive* drive = item->device().parent().as<Solid::OpticalDrive>();
322 if (drive) {
323 connect(drive, SIGNAL(ejectDone(Solid::ErrorType,QVariant,QString)),
324 this, SLOT(slotStorageTeardownDone(Solid::ErrorType,QVariant)));
325 drive->eject();
326 } else {
327 const QString label = item->text();
328 const QString message = i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label);
329 emit errorMessage(message);
330 }
331 }
332 }
333
334 void PlacesItemModel::requestTeardown(int index)
335 {
336 const PlacesItem* item = placesItem(index);
337 if (item) {
338 Solid::StorageAccess* access = item->device().as<Solid::StorageAccess>();
339 if (access) {
340 connect(access, SIGNAL(teardownDone(Solid::ErrorType,QVariant,QString)),
341 this, SLOT(slotStorageTeardownDone(Solid::ErrorType,QVariant)));
342 access->teardown();
343 }
344 }
345 }
346
347 bool PlacesItemModel::storageSetupNeeded(int index) const
348 {
349 const PlacesItem* item = placesItem(index);
350 return item ? item->storageSetupNeeded() : false;
351 }
352
353 void PlacesItemModel::requestStorageSetup(int index)
354 {
355 const PlacesItem* item = placesItem(index);
356 if (!item) {
357 return;
358 }
359
360 Solid::Device device = item->device();
361 const bool setup = device.is<Solid::StorageAccess>()
362 && !m_storageSetupInProgress.contains(device.as<Solid::StorageAccess>())
363 && !device.as<Solid::StorageAccess>()->isAccessible();
364 if (setup) {
365 Solid::StorageAccess* access = device.as<Solid::StorageAccess>();
366
367 m_storageSetupInProgress[access] = index;
368
369 connect(access, SIGNAL(setupDone(Solid::ErrorType,QVariant,QString)),
370 this, SLOT(slotStorageSetupDone(Solid::ErrorType,QVariant,QString)));
371
372 access->setup();
373 }
374 }
375
376 QMimeData* PlacesItemModel::createMimeData(const QSet<int>& indexes) const
377 {
378 KUrl::List urls;
379 QByteArray itemData;
380
381 QDataStream stream(&itemData, QIODevice::WriteOnly);
382
383 foreach (int index, indexes) {
384 const KUrl itemUrl = placesItem(index)->url();
385 if (itemUrl.isValid()) {
386 urls << itemUrl;
387 }
388 stream << index;
389 }
390
391 QMimeData* mimeData = new QMimeData();
392 if (!urls.isEmpty()) {
393 urls.populateMimeData(mimeData);
394 }
395 mimeData->setData(internalMimeType(), itemData);
396
397 return mimeData;
398 }
399
400 bool PlacesItemModel::supportsDropping(int index) const
401 {
402 return index >= 0 && index < count();
403 }
404
405 void PlacesItemModel::dropMimeDataBefore(int index, const QMimeData* mimeData)
406 {
407 if (mimeData->hasFormat(internalMimeType())) {
408 // The item has been moved inside the view
409 QByteArray itemData = mimeData->data(internalMimeType());
410 QDataStream stream(&itemData, QIODevice::ReadOnly);
411 int oldIndex;
412 stream >> oldIndex;
413 if (oldIndex == index || oldIndex == index - 1) {
414 // No moving has been done
415 return;
416 }
417
418 PlacesItem* oldItem = placesItem(oldIndex);
419 if (!oldItem) {
420 return;
421 }
422
423 PlacesItem* newItem = new PlacesItem(oldItem->bookmark());
424 removeItem(oldIndex);
425
426 if (oldIndex < index) {
427 --index;
428 }
429
430 const int dropIndex = groupedDropIndex(index, newItem);
431 insertItem(dropIndex, newItem);
432 } else if (mimeData->hasFormat("text/uri-list")) {
433 // One or more items must be added to the model
434 const KUrl::List urls = KUrl::List::fromMimeData(mimeData);
435 for (int i = urls.count() - 1; i >= 0; --i) {
436 const KUrl& url = urls[i];
437
438 QString text = url.fileName();
439 if (text.isEmpty()) {
440 text = url.host();
441 }
442
443 PlacesItem* newItem = createPlacesItem(text, url);
444 const int dropIndex = groupedDropIndex(index, newItem);
445 insertItem(dropIndex, newItem);
446 }
447 }
448 }
449
450 KUrl PlacesItemModel::convertedUrl(const KUrl& url)
451 {
452 KUrl newUrl = url;
453 if (url.protocol() == QLatin1String("timeline")) {
454 newUrl = createTimelineUrl(url);
455 } else if (url.protocol() == QLatin1String("search")) {
456 newUrl = createSearchUrl(url);
457 }
458
459 return newUrl;
460 }
461
462 void PlacesItemModel::onItemInserted(int index)
463 {
464 const PlacesItem* insertedItem = placesItem(index);
465 if (insertedItem) {
466 // Take care to apply the PlacesItemModel-order of the inserted item
467 // also to the bookmark-manager.
468 const KBookmark insertedBookmark = insertedItem->bookmark();
469
470 const PlacesItem* previousItem = placesItem(index - 1);
471 KBookmark previousBookmark;
472 if (previousItem) {
473 previousBookmark = previousItem->bookmark();
474 }
475
476 m_bookmarkManager->root().moveBookmark(insertedBookmark, previousBookmark);
477 }
478
479 if (index == count() - 1) {
480 // The item has been appended as last item to the list. In this
481 // case assure that it is also appended after the hidden items and
482 // not before (like done otherwise).
483 m_bookmarkedItems.append(0);
484 } else {
485
486 int modelIndex = -1;
487 int bookmarkIndex = 0;
488 while (bookmarkIndex < m_bookmarkedItems.count()) {
489 if (!m_bookmarkedItems[bookmarkIndex]) {
490 ++modelIndex;
491 if (modelIndex + 1 == index) {
492 break;
493 }
494 }
495 ++bookmarkIndex;
496 }
497 m_bookmarkedItems.insert(bookmarkIndex, 0);
498 }
499
500 triggerBookmarksSaving();
501
502 #ifdef PLACESITEMMODEL_DEBUG
503 kDebug() << "Inserted item" << index;
504 showModelState();
505 #endif
506 }
507
508 void PlacesItemModel::onItemRemoved(int index, KStandardItem* removedItem)
509 {
510 PlacesItem* placesItem = dynamic_cast<PlacesItem*>(removedItem);
511 if (placesItem) {
512 const KBookmark bookmark = placesItem->bookmark();
513 m_bookmarkManager->root().deleteBookmark(bookmark);
514 }
515
516 const int boomarkIndex = bookmarkIndex(index);
517 Q_ASSERT(!m_bookmarkedItems[boomarkIndex]);
518 m_bookmarkedItems.removeAt(boomarkIndex);
519
520 triggerBookmarksSaving();
521
522 #ifdef PLACESITEMMODEL_DEBUG
523 kDebug() << "Removed item" << index;
524 showModelState();
525 #endif
526 }
527
528 void PlacesItemModel::onItemChanged(int index, const QSet<QByteArray>& changedRoles)
529 {
530 const PlacesItem* changedItem = placesItem(index);
531 if (changedItem) {
532 // Take care to apply the PlacesItemModel-order of the changed item
533 // also to the bookmark-manager.
534 const KBookmark insertedBookmark = changedItem->bookmark();
535
536 const PlacesItem* previousItem = placesItem(index - 1);
537 KBookmark previousBookmark;
538 if (previousItem) {
539 previousBookmark = previousItem->bookmark();
540 }
541
542 m_bookmarkManager->root().moveBookmark(insertedBookmark, previousBookmark);
543 }
544
545 if (changedRoles.contains("isHidden")) {
546 if (!m_hiddenItemsShown && changedItem->isHidden()) {
547 m_hiddenItemToRemove = index;
548 QTimer::singleShot(0, this, SLOT(hideItem()));
549 }
550 }
551
552 triggerBookmarksSaving();
553 }
554
555 void PlacesItemModel::slotDeviceAdded(const QString& udi)
556 {
557 const Solid::Device device(udi);
558
559 if (!m_predicate.matches(device)) {
560 return;
561 }
562
563 m_availableDevices << udi;
564 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
565 appendItem(new PlacesItem(bookmark));
566 }
567
568 void PlacesItemModel::slotDeviceRemoved(const QString& udi)
569 {
570 if (!m_availableDevices.contains(udi)) {
571 return;
572 }
573
574 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
575 PlacesItem* item = m_bookmarkedItems[i];
576 if (item && item->udi() == udi) {
577 m_bookmarkedItems.removeAt(i);
578 delete item;
579 return;
580 }
581 }
582
583 for (int i = 0; i < count(); ++i) {
584 if (placesItem(i)->udi() == udi) {
585 removeItem(i);
586 return;
587 }
588 }
589 }
590
591 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error, const QVariant& errorData)
592 {
593 if (error && errorData.isValid()) {
594 emit errorMessage(errorData.toString());
595 }
596 }
597
598 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error,
599 const QVariant& errorData,
600 const QString& udi)
601 {
602 Q_UNUSED(udi);
603
604 const int index = m_storageSetupInProgress.take(sender());
605 const PlacesItem* item = placesItem(index);
606 if (!item) {
607 return;
608 }
609
610 if (error) {
611 // TODO: Request message-freeze exception
612 if (errorData.isValid()) {
613 // emit errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
614 // item->text(),
615 // errorData.toString()));
616 emit errorMessage(QString("An error occurred while accessing '%1', the system responded: %2")
617 .arg(item->text()).arg(errorData.toString()));
618 } else {
619 // emit errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
620 // item->text()));
621 emit errorMessage(QString("An error occurred while accessing '%1'").arg(item->text()));
622 }
623 emit storageSetupDone(index, false);
624 } else {
625 emit storageSetupDone(index, true);
626 }
627 }
628
629 void PlacesItemModel::hideItem()
630 {
631 hideItem(m_hiddenItemToRemove);
632 m_hiddenItemToRemove = -1;
633 }
634
635 void PlacesItemModel::updateBookmarks()
636 {
637 // Verify whether new bookmarks have been added or existing
638 // bookmarks have been changed.
639 KBookmarkGroup root = m_bookmarkManager->root();
640 KBookmark newBookmark = root.first();
641 while (!newBookmark.isNull()) {
642 if (acceptBookmark(newBookmark, m_availableDevices)) {
643 bool found = false;
644 int modelIndex = 0;
645 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
646 PlacesItem* item = m_bookmarkedItems[i];
647 if (!item) {
648 item = placesItem(modelIndex);
649 ++modelIndex;
650 }
651
652 const KBookmark oldBookmark = item->bookmark();
653 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
654 // The bookmark has been found in the model or as
655 // a hidden item. The content of the bookmark might
656 // have been changed, so an update is done.
657 found = true;
658 if (newBookmark.metaDataItem("UDI").isEmpty()) {
659 item->setBookmark(newBookmark);
660 }
661 break;
662 }
663 }
664
665 if (!found) {
666 const QString udi = newBookmark.metaDataItem("UDI");
667
668 /*
669 * See Bug 304878
670 * Only add a new places item, if the item text is not empty
671 * and if the device is available. Fixes the strange behaviour -
672 * add a places item without text in the Places section - when you
673 * remove a device (e.g. a usb stick) without unmounting.
674 */
675 if (udi.isEmpty() || Solid::Device(udi).isValid()) {
676 PlacesItem* item = new PlacesItem(newBookmark);
677 if (item->isHidden() && !m_hiddenItemsShown) {
678 m_bookmarkedItems.append(item);
679 } else {
680 appendItemToGroup(item);
681 }
682 }
683 }
684 }
685
686 newBookmark = root.next(newBookmark);
687 }
688
689 // Remove items that are not part of the bookmark-manager anymore
690 int modelIndex = 0;
691 for (int i = m_bookmarkedItems.count() - 1; i >= 0; --i) {
692 PlacesItem* item = m_bookmarkedItems[i];
693 const bool itemIsPartOfModel = (item == 0);
694 if (itemIsPartOfModel) {
695 item = placesItem(modelIndex);
696 }
697
698 bool hasBeenRemoved = true;
699 const KBookmark oldBookmark = item->bookmark();
700 KBookmark newBookmark = root.first();
701 while (!newBookmark.isNull()) {
702 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
703 hasBeenRemoved = false;
704 break;
705 }
706 newBookmark = root.next(newBookmark);
707 }
708
709 if (hasBeenRemoved) {
710 if (m_bookmarkedItems[i]) {
711 delete m_bookmarkedItems[i];
712 m_bookmarkedItems.removeAt(i);
713 } else {
714 removeItem(modelIndex);
715 --modelIndex;
716 }
717 }
718
719 if (itemIsPartOfModel) {
720 ++modelIndex;
721 }
722 }
723 }
724
725 void PlacesItemModel::saveBookmarks()
726 {
727 m_bookmarkManager->emitChanged(m_bookmarkManager->root());
728 }
729
730 void PlacesItemModel::loadBookmarks()
731 {
732 KBookmarkGroup root = m_bookmarkManager->root();
733 KBookmark bookmark = root.first();
734 QSet<QString> devices = m_availableDevices;
735
736 QSet<KUrl> missingSystemBookmarks;
737 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
738 missingSystemBookmarks.insert(data.url);
739 }
740
741 // The bookmarks might have a mixed order of places, devices and search-groups due
742 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
743 // items should always be collected in one group so the items are collected first
744 // in separate lists before inserting them.
745 QList<PlacesItem*> placesItems;
746 QList<PlacesItem*> recentlyAccessedItems;
747 QList<PlacesItem*> searchForItems;
748 QList<PlacesItem*> devicesItems;
749
750 while (!bookmark.isNull()) {
751 if (acceptBookmark(bookmark, devices)) {
752 PlacesItem* item = new PlacesItem(bookmark);
753 if (item->groupType() == PlacesItem::DevicesType) {
754 devices.remove(item->udi());
755 devicesItems.append(item);
756 } else {
757 const KUrl url = bookmark.url();
758 if (missingSystemBookmarks.contains(url)) {
759 missingSystemBookmarks.remove(url);
760
761 // Try to retranslate the text of system bookmarks to have translated
762 // items when changing the language. In case if the user has applied a custom
763 // text, the retranslation will fail and the users custom text is still used.
764 // It is important to use "KFile System Bookmarks" as context (see
765 // createSystemBookmarks()).
766 item->setText(i18nc("KFile System Bookmarks", bookmark.text().toUtf8().data()));
767 item->setSystemItem(true);
768 }
769
770 switch (item->groupType()) {
771 case PlacesItem::PlacesType: placesItems.append(item); break;
772 case PlacesItem::RecentlyAccessedType: recentlyAccessedItems.append(item); break;
773 case PlacesItem::SearchForType: searchForItems.append(item); break;
774 case PlacesItem::DevicesType:
775 default: Q_ASSERT(false); break;
776 }
777 }
778 }
779
780 bookmark = root.next(bookmark);
781 }
782
783 if (!missingSystemBookmarks.isEmpty()) {
784 // The current bookmarks don't contain all system-bookmarks. Add the missing
785 // bookmarks.
786 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
787 if (missingSystemBookmarks.contains(data.url)) {
788 PlacesItem* item = createSystemPlacesItem(data);
789 switch (item->groupType()) {
790 case PlacesItem::PlacesType: placesItems.append(item); break;
791 case PlacesItem::RecentlyAccessedType: recentlyAccessedItems.append(item); break;
792 case PlacesItem::SearchForType: searchForItems.append(item); break;
793 case PlacesItem::DevicesType:
794 default: Q_ASSERT(false); break;
795 }
796 }
797 }
798 }
799
800 // Create items for devices that have not been stored as bookmark yet
801 foreach (const QString& udi, devices) {
802 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
803 devicesItems.append(new PlacesItem(bookmark));
804 }
805
806 QList<PlacesItem*> items;
807 items.append(placesItems);
808 items.append(recentlyAccessedItems);
809 items.append(searchForItems);
810 items.append(devicesItems);
811
812 foreach (PlacesItem* item, items) {
813 if (!m_hiddenItemsShown && item->isHidden()) {
814 m_bookmarkedItems.append(item);
815 } else {
816 appendItem(item);
817 }
818 }
819
820 #ifdef PLACESITEMMODEL_DEBUG
821 kDebug() << "Loaded bookmarks";
822 showModelState();
823 #endif
824 }
825
826 bool PlacesItemModel::acceptBookmark(const KBookmark& bookmark,
827 const QSet<QString>& availableDevices) const
828 {
829 const QString udi = bookmark.metaDataItem("UDI");
830 const KUrl url = bookmark.url();
831 const QString appName = bookmark.metaDataItem("OnlyInApp");
832 const bool deviceAvailable = availableDevices.contains(udi);
833
834 const bool allowedHere = (appName.isEmpty()
835 || appName == KGlobal::mainComponent().componentName()
836 || appName == KGlobal::mainComponent().componentName() + AppNamePrefix)
837 && (m_fileIndexingEnabled || (url.protocol() != QLatin1String("timeline") &&
838 url.protocol() != QLatin1String("search")));
839
840 return (udi.isEmpty() && allowedHere) || deviceAvailable;
841 }
842
843 PlacesItem* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData& data)
844 {
845 KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager,
846 data.text,
847 data.url,
848 data.icon);
849
850 const QString protocol = data.url.protocol();
851 if (protocol == QLatin1String("timeline") || protocol == QLatin1String("search")) {
852 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
853 // for "Recently Accessed" and "Search For" should be a setting available only
854 // in the Places Panel (see description of AppNamePrefix for more details).
855 const QString appName = KGlobal::mainComponent().componentName() + AppNamePrefix;
856 bookmark.setMetaDataItem("OnlyInApp", appName);
857 }
858
859 PlacesItem* item = new PlacesItem(bookmark);
860 item->setSystemItem(true);
861
862 // Create default view-properties for all "Search For" and "Recently Accessed" bookmarks
863 // in case if the user has not already created custom view-properties for a corresponding
864 // query yet.
865 const bool createDefaultViewProperties = (item->groupType() == PlacesItem::SearchForType ||
866 item->groupType() == PlacesItem::RecentlyAccessedType) &&
867 !GeneralSettings::self()->globalViewProps();
868 if (createDefaultViewProperties) {
869 ViewProperties props(convertedUrl(data.url));
870 if (!props.exist()) {
871 const QString path = data.url.path();
872 if (path == QLatin1String("/documents")) {
873 props.setViewMode(DolphinView::DetailsView);
874 props.setPreviewsShown(false);
875 props.setVisibleRoles(QList<QByteArray>() << "text" << "path");
876 } else if (path == QLatin1String("/images")) {
877 props.setViewMode(DolphinView::IconsView);
878 props.setPreviewsShown(true);
879 props.setVisibleRoles(QList<QByteArray>() << "text" << "imageSize");
880 } else if (path == QLatin1String("/audio")) {
881 props.setViewMode(DolphinView::DetailsView);
882 props.setPreviewsShown(false);
883 props.setVisibleRoles(QList<QByteArray>() << "text" << "artist" << "album");
884 } else if (path == QLatin1String("/videos")) {
885 props.setViewMode(DolphinView::IconsView);
886 props.setPreviewsShown(true);
887 props.setVisibleRoles(QList<QByteArray>() << "text");
888 } else if (data.url.protocol() == "timeline") {
889 props.setViewMode(DolphinView::DetailsView);
890 props.setVisibleRoles(QList<QByteArray>() << "text" << "date");
891 }
892 }
893 }
894
895 return item;
896 }
897
898 void PlacesItemModel::createSystemBookmarks()
899 {
900 Q_ASSERT(m_systemBookmarks.isEmpty());
901 Q_ASSERT(m_systemBookmarksIndexes.isEmpty());
902
903 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
904 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
905 // done here is because otherwise switching the language would not result in retranslating the
906 // bookmarks.
907 m_systemBookmarks.append(SystemBookmarkData(KUrl(KUser().homeDir()),
908 "user-home",
909 I18N_NOOP2("KFile System Bookmarks", "Home")));
910 m_systemBookmarks.append(SystemBookmarkData(KUrl("remote:/"),
911 "network-workgroup",
912 I18N_NOOP2("KFile System Bookmarks", "Network")));
913 m_systemBookmarks.append(SystemBookmarkData(KUrl("/"),
914 "folder-red",
915 I18N_NOOP2("KFile System Bookmarks", "Root")));
916 m_systemBookmarks.append(SystemBookmarkData(KUrl("trash:/"),
917 "user-trash",
918 I18N_NOOP2("KFile System Bookmarks", "Trash")));
919
920 if (m_fileIndexingEnabled) {
921 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/today"),
922 "go-jump-today",
923 I18N_NOOP2("KFile System Bookmarks", "Today")));
924 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/yesterday"),
925 "view-calendar-day",
926 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
927 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/thismonth"),
928 "view-calendar-month",
929 I18N_NOOP2("KFile System Bookmarks", "This Month")));
930 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/lastmonth"),
931 "view-calendar-month",
932 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
933 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/documents"),
934 "folder-txt",
935 I18N_NOOP2("KFile System Bookmarks", "Documents")));
936 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/images"),
937 "folder-image",
938 I18N_NOOP2("KFile System Bookmarks", "Images")));
939 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/audio"),
940 "folder-sound",
941 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
942 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/videos"),
943 "folder-video",
944 I18N_NOOP2("KFile System Bookmarks", "Videos")));
945 }
946
947 for (int i = 0; i < m_systemBookmarks.count(); ++i) {
948 m_systemBookmarksIndexes.insert(m_systemBookmarks[i].url, i);
949 }
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 Nepomuk-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_NEPOMUK
1160 const QString path = url.pathOrUrl();
1161 if (path.endsWith(QLatin1String("documents"))) {
1162 searchUrl = searchUrlForTerm(Nepomuk2::Query::ResourceTypeTerm(Nepomuk2::Vocabulary::NFO::Document()));
1163 } else if (path.endsWith(QLatin1String("images"))) {
1164 searchUrl = searchUrlForTerm(Nepomuk2::Query::ResourceTypeTerm(Nepomuk2::Vocabulary::NFO::Image()));
1165 } else if (path.endsWith(QLatin1String("audio"))) {
1166 searchUrl = searchUrlForTerm(Nepomuk2::Query::ComparisonTerm(Nepomuk2::Vocabulary::NIE::mimeType(),
1167 Nepomuk2::Query::LiteralTerm("audio")));
1168 } else if (path.endsWith(QLatin1String("videos"))) {
1169 searchUrl = searchUrlForTerm(Nepomuk2::Query::ComparisonTerm(Nepomuk2::Vocabulary::NIE::mimeType(),
1170 Nepomuk2::Query::LiteralTerm("video")));
1171 } else {
1172 Q_ASSERT(false);
1173 }
1174 #else
1175 Q_UNUSED(url);
1176 #endif
1177
1178 return searchUrl;
1179 }
1180
1181 #ifdef HAVE_NEPOMUK
1182 KUrl PlacesItemModel::searchUrlForTerm(const Nepomuk2::Query::Term& term)
1183 {
1184 const Nepomuk2::Query::FileQuery query(term);
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"