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