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