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