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