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