]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/places/placesitemmodel.cpp
Re-implement dropping of files on folders in the Places Panel.
[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_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 (Nepomuk::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 PlacesItem* item = new PlacesItem(newBookmark);
663 if (item->isHidden() && !m_hiddenItemsShown) {
664 m_bookmarkedItems.append(item);
665 } else {
666 appendItemToGroup(item);
667 }
668 }
669 }
670
671 newBookmark = root.next(newBookmark);
672 }
673
674 // Remove items that are not part of the bookmark-manager anymore
675 int modelIndex = 0;
676 for (int i = m_bookmarkedItems.count() - 1; i >= 0; --i) {
677 PlacesItem* item = m_bookmarkedItems[i];
678 const bool itemIsPartOfModel = (item == 0);
679 if (itemIsPartOfModel) {
680 item = placesItem(modelIndex);
681 }
682
683 bool hasBeenRemoved = true;
684 const KBookmark oldBookmark = item->bookmark();
685 KBookmark newBookmark = root.first();
686 while (!newBookmark.isNull()) {
687 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
688 hasBeenRemoved = false;
689 break;
690 }
691 newBookmark = root.next(newBookmark);
692 }
693
694 if (hasBeenRemoved) {
695 if (m_bookmarkedItems[i]) {
696 delete m_bookmarkedItems[i];
697 m_bookmarkedItems.removeAt(i);
698 } else {
699 removeItem(modelIndex);
700 --modelIndex;
701 }
702 }
703
704 if (itemIsPartOfModel) {
705 ++modelIndex;
706 }
707 }
708 }
709
710 void PlacesItemModel::saveBookmarks()
711 {
712 m_bookmarkManager->emitChanged(m_bookmarkManager->root());
713 }
714
715 void PlacesItemModel::loadBookmarks()
716 {
717 KBookmarkGroup root = m_bookmarkManager->root();
718 KBookmark bookmark = root.first();
719 QSet<QString> devices = m_availableDevices;
720
721 QSet<KUrl> missingSystemBookmarks;
722 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
723 missingSystemBookmarks.insert(data.url);
724 }
725
726 // The bookmarks might have a mixed order of places, devices and search-groups due
727 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
728 // items should always be collected in one group so the items are collected first
729 // in separate lists before inserting them.
730 QList<PlacesItem*> placesItems;
731 QList<PlacesItem*> recentlyAccessedItems;
732 QList<PlacesItem*> searchForItems;
733 QList<PlacesItem*> devicesItems;
734
735 while (!bookmark.isNull()) {
736 if (acceptBookmark(bookmark, devices)) {
737 PlacesItem* item = new PlacesItem(bookmark);
738 if (item->groupType() == PlacesItem::DevicesType) {
739 devices.remove(item->udi());
740 devicesItems.append(item);
741 } else {
742 const KUrl url = bookmark.url();
743 if (missingSystemBookmarks.contains(url)) {
744 missingSystemBookmarks.remove(url);
745
746 // Try to retranslate the text of system bookmarks to have translated
747 // items when changing the language. In case if the user has applied a custom
748 // text, the retranslation will fail and the users custom text is still used.
749 // It is important to use "KFile System Bookmarks" as context (see
750 // createSystemBookmarks()).
751 item->setText(i18nc("KFile System Bookmarks", bookmark.text().toUtf8().data()));
752 item->setSystemItem(true);
753 }
754
755 switch (item->groupType()) {
756 case PlacesItem::PlacesType: placesItems.append(item); break;
757 case PlacesItem::RecentlyAccessedType: recentlyAccessedItems.append(item); break;
758 case PlacesItem::SearchForType: searchForItems.append(item); break;
759 case PlacesItem::DevicesType:
760 default: Q_ASSERT(false); break;
761 }
762 }
763 }
764
765 bookmark = root.next(bookmark);
766 }
767
768 if (!missingSystemBookmarks.isEmpty()) {
769 // The current bookmarks don't contain all system-bookmarks. Add the missing
770 // bookmarks.
771 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
772 if (missingSystemBookmarks.contains(data.url)) {
773 PlacesItem* item = createSystemPlacesItem(data);
774 switch (item->groupType()) {
775 case PlacesItem::PlacesType: placesItems.append(item); break;
776 case PlacesItem::RecentlyAccessedType: recentlyAccessedItems.append(item); break;
777 case PlacesItem::SearchForType: searchForItems.append(item); break;
778 case PlacesItem::DevicesType:
779 default: Q_ASSERT(false); break;
780 }
781 }
782 }
783 }
784
785 // Create items for devices that have not been stored as bookmark yet
786 foreach (const QString& udi, devices) {
787 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
788 devicesItems.append(new PlacesItem(bookmark));
789 }
790
791 QList<PlacesItem*> items;
792 items.append(placesItems);
793 items.append(recentlyAccessedItems);
794 items.append(searchForItems);
795 items.append(devicesItems);
796
797 foreach (PlacesItem* item, items) {
798 if (!m_hiddenItemsShown && item->isHidden()) {
799 m_bookmarkedItems.append(item);
800 } else {
801 appendItem(item);
802 }
803 }
804
805 #ifdef PLACESITEMMODEL_DEBUG
806 kDebug() << "Loaded bookmarks";
807 showModelState();
808 #endif
809 }
810
811 bool PlacesItemModel::acceptBookmark(const KBookmark& bookmark,
812 const QSet<QString>& availableDevices) const
813 {
814 const QString udi = bookmark.metaDataItem("UDI");
815 const KUrl url = bookmark.url();
816 const QString appName = bookmark.metaDataItem("OnlyInApp");
817 const bool deviceAvailable = availableDevices.contains(udi);
818
819 const bool allowedHere = (appName.isEmpty()
820 || appName == KGlobal::mainComponent().componentName()
821 || appName == KGlobal::mainComponent().componentName() + AppNamePrefix)
822 && (m_fileIndexingEnabled || (url.protocol() != QLatin1String("timeline") &&
823 url.protocol() != QLatin1String("search")));
824
825 return (udi.isEmpty() && allowedHere) || deviceAvailable;
826 }
827
828 PlacesItem* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData& data)
829 {
830 KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager,
831 data.text,
832 data.url,
833 data.icon);
834
835 const QString protocol = data.url.protocol();
836 if (protocol == QLatin1String("timeline") || protocol == QLatin1String("search")) {
837 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
838 // for "Recently Accessed" and "Search For" should be a setting available only
839 // in the Places Panel (see description of AppNamePrefix for more details).
840 const QString appName = KGlobal::mainComponent().componentName() + AppNamePrefix;
841 bookmark.setMetaDataItem("OnlyInApp", appName);
842 }
843
844 PlacesItem* item = new PlacesItem(bookmark);
845 item->setSystemItem(true);
846
847 // Create default view-properties for all "Search For" and "Recently Accessed" bookmarks
848 // in case if the user has not already created custom view-properties for a corresponding
849 // query yet.
850 const bool createDefaultViewProperties = (item->groupType() == PlacesItem::SearchForType ||
851 item->groupType() == PlacesItem::RecentlyAccessedType) &&
852 !GeneralSettings::self()->globalViewProps();
853 if (createDefaultViewProperties) {
854 ViewProperties props(convertedUrl(data.url));
855 if (!props.exist()) {
856 const QString path = data.url.path();
857 if (path == QLatin1String("/documents")) {
858 props.setViewMode(DolphinView::DetailsView);
859 props.setPreviewsShown(false);
860 props.setVisibleRoles(QList<QByteArray>() << "text" << "path");
861 } else if (path == QLatin1String("/images")) {
862 props.setViewMode(DolphinView::IconsView);
863 props.setPreviewsShown(true);
864 props.setVisibleRoles(QList<QByteArray>() << "text" << "imageSize");
865 } else if (path == QLatin1String("/audio")) {
866 props.setViewMode(DolphinView::DetailsView);
867 props.setPreviewsShown(false);
868 props.setVisibleRoles(QList<QByteArray>() << "text" << "artist" << "album");
869 } else if (path == QLatin1String("/videos")) {
870 props.setViewMode(DolphinView::IconsView);
871 props.setPreviewsShown(true);
872 props.setVisibleRoles(QList<QByteArray>() << "text");
873 } else if (data.url.protocol() == "timeline") {
874 props.setViewMode(DolphinView::DetailsView);
875 props.setVisibleRoles(QList<QByteArray>() << "text" << "date");
876 }
877 }
878 }
879
880 return item;
881 }
882
883 void PlacesItemModel::createSystemBookmarks()
884 {
885 Q_ASSERT(m_systemBookmarks.isEmpty());
886 Q_ASSERT(m_systemBookmarksIndexes.isEmpty());
887
888 const QString timeLineIcon = "package_utility_time"; // TODO: Ask the Oxygen team to create
889 // a custom icon for the timeline-protocol
890
891 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
892 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
893 // done here is because otherwise switching the language would not result in retranslating the
894 // bookmarks.
895 m_systemBookmarks.append(SystemBookmarkData(KUrl(KUser().homeDir()),
896 "user-home",
897 I18N_NOOP2("KFile System Bookmarks", "Home")));
898 m_systemBookmarks.append(SystemBookmarkData(KUrl("remote:/"),
899 "network-workgroup",
900 I18N_NOOP2("KFile System Bookmarks", "Network")));
901 m_systemBookmarks.append(SystemBookmarkData(KUrl("/"),
902 "folder-red",
903 I18N_NOOP2("KFile System Bookmarks", "Root")));
904 m_systemBookmarks.append(SystemBookmarkData(KUrl("trash:/"),
905 "user-trash",
906 I18N_NOOP2("KFile System Bookmarks", "Trash")));
907
908 if (m_fileIndexingEnabled) {
909 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/today"),
910 timeLineIcon,
911 I18N_NOOP2("KFile System Bookmarks", "Today")));
912 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/yesterday"),
913 timeLineIcon,
914 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
915 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/thismonth"),
916 timeLineIcon,
917 I18N_NOOP2("KFile System Bookmarks", "This Month")));
918 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/lastmonth"),
919 timeLineIcon,
920 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
921 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/documents"),
922 "folder-txt",
923 I18N_NOOP2("KFile System Bookmarks", "Documents")));
924 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/images"),
925 "folder-image",
926 I18N_NOOP2("KFile System Bookmarks", "Images")));
927 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/audio"),
928 "folder-sound",
929 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
930 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/videos"),
931 "folder-video",
932 I18N_NOOP2("KFile System Bookmarks", "Videos")));
933 }
934
935 for (int i = 0; i < m_systemBookmarks.count(); ++i) {
936 m_systemBookmarksIndexes.insert(m_systemBookmarks[i].url, i);
937 }
938 }
939
940 void PlacesItemModel::initializeAvailableDevices()
941 {
942 m_predicate = Solid::Predicate::fromString(
943 "[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
944 " OR "
945 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
946 " OR "
947 "OpticalDisc.availableContent & 'Audio' ]"
948 " OR "
949 "StorageAccess.ignored == false ]");
950 Q_ASSERT(m_predicate.isValid());
951
952 Solid::DeviceNotifier* notifier = Solid::DeviceNotifier::instance();
953 connect(notifier, SIGNAL(deviceAdded(QString)), this, SLOT(slotDeviceAdded(QString)));
954 connect(notifier, SIGNAL(deviceRemoved(QString)), this, SLOT(slotDeviceRemoved(QString)));
955
956 const QList<Solid::Device>& deviceList = Solid::Device::listFromQuery(m_predicate);
957 foreach (const Solid::Device& device, deviceList) {
958 m_availableDevices << device.udi();
959 }
960 }
961
962 int PlacesItemModel::bookmarkIndex(int index) const
963 {
964 int bookmarkIndex = 0;
965 int modelIndex = 0;
966 while (bookmarkIndex < m_bookmarkedItems.count()) {
967 if (!m_bookmarkedItems[bookmarkIndex]) {
968 if (modelIndex == index) {
969 break;
970 }
971 ++modelIndex;
972 }
973 ++bookmarkIndex;
974 }
975
976 return bookmarkIndex >= m_bookmarkedItems.count() ? -1 : bookmarkIndex;
977 }
978
979 void PlacesItemModel::hideItem(int index)
980 {
981 PlacesItem* shownItem = placesItem(index);
982 if (!shownItem) {
983 return;
984 }
985
986 shownItem->setHidden(true);
987 if (m_hiddenItemsShown) {
988 // Removing items from the model is not allowed if all hidden
989 // items should be shown.
990 return;
991 }
992
993 const int newIndex = bookmarkIndex(index);
994 if (newIndex >= 0) {
995 const KBookmark hiddenBookmark = shownItem->bookmark();
996 PlacesItem* hiddenItem = new PlacesItem(hiddenBookmark);
997
998 const PlacesItem* previousItem = placesItem(index - 1);
999 KBookmark previousBookmark;
1000 if (previousItem) {
1001 previousBookmark = previousItem->bookmark();
1002 }
1003
1004 const bool updateBookmark = (m_bookmarkManager->root().indexOf(hiddenBookmark) >= 0);
1005 removeItem(index);
1006
1007 if (updateBookmark) {
1008 // removeItem() also removed the bookmark from m_bookmarkManager in
1009 // PlacesItemModel::onItemRemoved(). However for hidden items the
1010 // bookmark should still be remembered, so readd it again:
1011 m_bookmarkManager->root().addBookmark(hiddenBookmark);
1012 m_bookmarkManager->root().moveBookmark(hiddenBookmark, previousBookmark);
1013 triggerBookmarksSaving();
1014 }
1015
1016 m_bookmarkedItems.insert(newIndex, hiddenItem);
1017 }
1018 }
1019
1020 void PlacesItemModel::triggerBookmarksSaving()
1021 {
1022 if (m_saveBookmarksTimer) {
1023 m_saveBookmarksTimer->start();
1024 }
1025 }
1026
1027 QString PlacesItemModel::internalMimeType() const
1028 {
1029 return "application/x-dolphinplacesmodel-" +
1030 QString::number((qptrdiff)this);
1031 }
1032
1033 int PlacesItemModel::groupedDropIndex(int index, const PlacesItem* item) const
1034 {
1035 Q_ASSERT(item);
1036
1037 int dropIndex = index;
1038 const PlacesItem::GroupType type = item->groupType();
1039
1040 const int itemCount = count();
1041 if (index < 0) {
1042 dropIndex = itemCount;
1043 }
1044
1045 // Search nearest previous item with the same group
1046 int previousIndex = -1;
1047 for (int i = dropIndex - 1; i >= 0; --i) {
1048 if (placesItem(i)->groupType() == type) {
1049 previousIndex = i;
1050 break;
1051 }
1052 }
1053
1054 // Search nearest next item with the same group
1055 int nextIndex = -1;
1056 for (int i = dropIndex; i < count(); ++i) {
1057 if (placesItem(i)->groupType() == type) {
1058 nextIndex = i;
1059 break;
1060 }
1061 }
1062
1063 // Adjust the drop-index to be inserted to the
1064 // nearest item with the same group.
1065 if (previousIndex >= 0 && nextIndex >= 0) {
1066 dropIndex = (dropIndex - previousIndex < nextIndex - dropIndex) ?
1067 previousIndex + 1 : nextIndex;
1068 } else if (previousIndex >= 0) {
1069 dropIndex = previousIndex + 1;
1070 } else if (nextIndex >= 0) {
1071 dropIndex = nextIndex;
1072 }
1073
1074 return dropIndex;
1075 }
1076
1077 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark& b1, const KBookmark& b2)
1078 {
1079 const QString udi1 = b1.metaDataItem("UDI");
1080 const QString udi2 = b2.metaDataItem("UDI");
1081 if (!udi1.isEmpty() && !udi2.isEmpty()) {
1082 return udi1 == udi2;
1083 } else {
1084 return b1.metaDataItem("ID") == b2.metaDataItem("ID");
1085 }
1086 }
1087
1088 KUrl PlacesItemModel::createTimelineUrl(const KUrl& url)
1089 {
1090 // TODO: Clarify with the Nepomuk-team whether it makes sense
1091 // provide default-timeline-URLs like 'yesterday', 'this month'
1092 // and 'last month'.
1093 KUrl timelineUrl;
1094
1095 const QString path = url.pathOrUrl();
1096 if (path.endsWith(QLatin1String("yesterday"))) {
1097 const QDate date = QDate::currentDate().addDays(-1);
1098 const int year = date.year();
1099 const int month = date.month();
1100 const int day = date.day();
1101 timelineUrl = "timeline:/" + timelineDateString(year, month) +
1102 '/' + timelineDateString(year, month, day);
1103 } else if (path.endsWith(QLatin1String("thismonth"))) {
1104 const QDate date = QDate::currentDate();
1105 timelineUrl = "timeline:/" + timelineDateString(date.year(), date.month());
1106 } else if (path.endsWith(QLatin1String("lastmonth"))) {
1107 const QDate date = QDate::currentDate().addMonths(-1);
1108 timelineUrl = "timeline:/" + timelineDateString(date.year(), date.month());
1109 } else {
1110 Q_ASSERT(path.endsWith(QLatin1String("today")));
1111 timelineUrl= url;
1112 }
1113
1114 return timelineUrl;
1115 }
1116
1117 QString PlacesItemModel::timelineDateString(int year, int month, int day)
1118 {
1119 QString date = QString::number(year) + '-';
1120 if (month < 10) {
1121 date += '0';
1122 }
1123 date += QString::number(month);
1124
1125 if (day >= 1) {
1126 date += '-';
1127 if (day < 10) {
1128 date += '0';
1129 }
1130 date += QString::number(day);
1131 }
1132
1133 return date;
1134 }
1135
1136 KUrl PlacesItemModel::createSearchUrl(const KUrl& url)
1137 {
1138 KUrl searchUrl;
1139
1140 #ifdef HAVE_NEPOMUK
1141 const QString path = url.pathOrUrl();
1142 if (path.endsWith(QLatin1String("documents"))) {
1143 searchUrl = searchUrlForTerm(Nepomuk::Query::ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Document()));
1144 } else if (path.endsWith(QLatin1String("images"))) {
1145 searchUrl = searchUrlForTerm(Nepomuk::Query::ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Image()));
1146 } else if (path.endsWith(QLatin1String("audio"))) {
1147 searchUrl = searchUrlForTerm(Nepomuk::Query::ComparisonTerm(Nepomuk::Vocabulary::NIE::mimeType(),
1148 Nepomuk::Query::LiteralTerm("audio")));
1149 } else if (path.endsWith(QLatin1String("videos"))) {
1150 searchUrl = searchUrlForTerm(Nepomuk::Query::ComparisonTerm(Nepomuk::Vocabulary::NIE::mimeType(),
1151 Nepomuk::Query::LiteralTerm("video")));
1152 } else {
1153 Q_ASSERT(false);
1154 }
1155 #else
1156 Q_UNUSED(url);
1157 #endif
1158
1159 return searchUrl;
1160 }
1161
1162 #ifdef HAVE_NEPOMUK
1163 KUrl PlacesItemModel::searchUrlForTerm(const Nepomuk::Query::Term& term)
1164 {
1165 const Nepomuk::Query::Query query(term);
1166 return query.toSearchUrl();
1167 }
1168 #endif
1169
1170 #ifdef PLACESITEMMODEL_DEBUG
1171 void PlacesItemModel::showModelState()
1172 {
1173 kDebug() << "=================================";
1174 kDebug() << "Model:";
1175 kDebug() << "hidden-index model-index text";
1176 int modelIndex = 0;
1177 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
1178 if (m_bookmarkedItems[i]) {
1179 kDebug() << i << "(Hidden) " << " " << m_bookmarkedItems[i]->dataValue("text").toString();
1180 } else {
1181 if (item(modelIndex)) {
1182 kDebug() << i << " " << modelIndex << " " << item(modelIndex)->dataValue("text").toString();
1183 } else {
1184 kDebug() << i << " " << modelIndex << " " << "(not available yet)";
1185 }
1186 ++modelIndex;
1187 }
1188 }
1189
1190 kDebug();
1191 kDebug() << "Bookmarks:";
1192
1193 int bookmarkIndex = 0;
1194 KBookmarkGroup root = m_bookmarkManager->root();
1195 KBookmark bookmark = root.first();
1196 while (!bookmark.isNull()) {
1197 const QString udi = bookmark.metaDataItem("UDI");
1198 const QString text = udi.isEmpty() ? bookmark.text() : udi;
1199 if (bookmark.metaDataItem("IsHidden") == QLatin1String("true")) {
1200 kDebug() << bookmarkIndex << "(Hidden)" << text;
1201 } else {
1202 kDebug() << bookmarkIndex << " " << text;
1203 }
1204
1205 bookmark = root.next(bookmark);
1206 ++bookmarkIndex;
1207 }
1208 }
1209 #endif
1210
1211 #include "placesitemmodel.moc"