]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/places/placesitemmodel.cpp
Enable basic drag and drop support for the Places Panel
[dolphin.git] / src / panels / places / placesitemmodel.cpp
1 /***************************************************************************
2 * Copyright (C) 2012 by Peter Penz <peter.penz19@gmail.com> *
3 * *
4 * Based on KFilePlacesModel from kdelibs: *
5 * Copyright (C) 2007 Kevin Ottens <ervin@kde.org> *
6 * Copyright (C) 2007 David Faure <faure@kde.org> *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
22 ***************************************************************************/
23
24 #include "placesitemmodel.h"
25
26 #include "dolphin_generalsettings.h"
27
28 #include <KBookmark>
29 #include <KBookmarkGroup>
30 #include <KBookmarkManager>
31 #include <KComponentData>
32 #include <KDebug>
33 #include <KIcon>
34 #include <KLocale>
35 #include <KStandardDirs>
36 #include <KUser>
37 #include "placesitem.h"
38 #include <QAction>
39 #include <QDate>
40 #include <QMimeData>
41 #include <QTimer>
42
43 #include <Solid/Device>
44 #include <Solid/DeviceNotifier>
45 #include <Solid/OpticalDisc>
46 #include <Solid/OpticalDrive>
47 #include <Solid/StorageAccess>
48 #include <Solid/StorageDrive>
49
50 #include <views/dolphinview.h>
51 #include <views/viewproperties.h>
52
53 #ifdef HAVE_NEPOMUK
54 #include <Nepomuk/ResourceManager>
55 #include <Nepomuk/Query/ComparisonTerm>
56 #include <Nepomuk/Query/LiteralTerm>
57 #include <Nepomuk/Query/Query>
58 #include <Nepomuk/Query/ResourceTypeTerm>
59 #include <Nepomuk/Vocabulary/NFO>
60 #include <Nepomuk/Vocabulary/NIE>
61 #endif
62
63 namespace {
64 // As long as KFilePlacesView from kdelibs is available in parallel, the
65 // system-bookmarks for "Recently Accessed" and "Search For" should be
66 // shown only inside the Places Panel. This is necessary as the stored
67 // URLs needs to get translated to a Nepomuk-search-URL on-the-fly to
68 // be independent from changes in the Nepomuk-search-URL-syntax.
69 // Hence a prefix to the application-name of the stored bookmarks is
70 // added, which is only read by PlacesItemModel.
71 const char* AppNamePrefix = "-places-panel";
72 }
73
74 PlacesItemModel::PlacesItemModel(QObject* parent) :
75 KStandardItemModel(parent),
76 m_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 = 1000;
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
335 const QString internalMimeType = "application/x-dolphinplacesmodel-" +
336 QString::number((qptrdiff)this);
337 mimeData->setData(internalMimeType, itemData);
338
339 return mimeData;
340 }
341
342 bool PlacesItemModel::supportsDropping(int index) const
343 {
344 Q_UNUSED(index);
345 return true;
346 }
347
348 KUrl PlacesItemModel::convertedUrl(const KUrl& url)
349 {
350 KUrl newUrl = url;
351 if (url.protocol() == QLatin1String("timeline")) {
352 newUrl = createTimelineUrl(url);
353 } else if (url.protocol() == QLatin1String("search")) {
354 newUrl = createSearchUrl(url);
355 }
356
357 return newUrl;
358 }
359
360 void PlacesItemModel::onItemInserted(int index)
361 {
362 const PlacesItem* insertedItem = placesItem(index);
363 if (insertedItem) {
364 // Take care to apply the PlacesItemModel-order of the inserted item
365 // also to the bookmark-manager.
366 const KBookmark insertedBookmark = insertedItem->bookmark();
367
368 const PlacesItem* previousItem = placesItem(index - 1);
369 KBookmark previousBookmark;
370 if (previousItem) {
371 previousBookmark = previousItem->bookmark();
372 }
373
374 m_bookmarkManager->root().moveBookmark(insertedBookmark, previousBookmark);
375 }
376
377 if (index == count() - 1) {
378 // The item has been appended as last item to the list. In this
379 // case assure that it is also appended after the hidden items and
380 // not before (like done otherwise).
381 m_bookmarkedItems.append(0);
382 } else {
383
384 int modelIndex = -1;
385 int bookmarkIndex = 0;
386 while (bookmarkIndex < m_bookmarkedItems.count()) {
387 if (!m_bookmarkedItems[bookmarkIndex]) {
388 ++modelIndex;
389 if (modelIndex + 1 == index) {
390 break;
391 }
392 }
393 ++bookmarkIndex;
394 }
395 m_bookmarkedItems.insert(bookmarkIndex, 0);
396 }
397
398 triggerBookmarksSaving();
399
400 #ifdef PLACESITEMMODEL_DEBUG
401 kDebug() << "Inserted item" << index;
402 showModelState();
403 #endif
404 }
405
406 void PlacesItemModel::onItemRemoved(int index, KStandardItem* removedItem)
407 {
408 PlacesItem* placesItem = dynamic_cast<PlacesItem*>(removedItem);
409 if (placesItem) {
410 const KBookmark bookmark = placesItem->bookmark();
411 m_bookmarkManager->root().deleteBookmark(bookmark);
412 }
413
414 const int boomarkIndex = bookmarkIndex(index);
415 Q_ASSERT(!m_bookmarkedItems[boomarkIndex]);
416 m_bookmarkedItems.removeAt(boomarkIndex);
417
418 triggerBookmarksSaving();
419
420 #ifdef PLACESITEMMODEL_DEBUG
421 kDebug() << "Removed item" << index;
422 showModelState();
423 #endif
424 }
425
426 void PlacesItemModel::onItemChanged(int index, const QSet<QByteArray>& changedRoles)
427 {
428 const PlacesItem* changedItem = placesItem(index);
429 if (changedItem) {
430 // Take care to apply the PlacesItemModel-order of the changed item
431 // also to the bookmark-manager.
432 const KBookmark insertedBookmark = changedItem->bookmark();
433
434 const PlacesItem* previousItem = placesItem(index - 1);
435 KBookmark previousBookmark;
436 if (previousItem) {
437 previousBookmark = previousItem->bookmark();
438 }
439
440 m_bookmarkManager->root().moveBookmark(insertedBookmark, previousBookmark);
441 }
442
443 if (changedRoles.contains("isHidden")) {
444 if (!m_hiddenItemsShown && changedItem->isHidden()) {
445 m_hiddenItemToRemove = index;
446 QTimer::singleShot(0, this, SLOT(hideItem()));
447 }
448 }
449
450 triggerBookmarksSaving();
451 }
452
453 void PlacesItemModel::slotDeviceAdded(const QString& udi)
454 {
455 const Solid::Device device(udi);
456 if (m_predicate.matches(device)) {
457 m_availableDevices << udi;
458 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
459 appendItem(new PlacesItem(bookmark));
460 }
461 }
462
463 void PlacesItemModel::slotDeviceRemoved(const QString& udi)
464 {
465 if (!m_availableDevices.contains(udi)) {
466 return;
467 }
468
469 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
470 PlacesItem* item = m_bookmarkedItems[i];
471 if (item && item->udi() == udi) {
472 m_bookmarkedItems.removeAt(i);
473 delete item;
474 return;
475 }
476 }
477
478 for (int i = 0; i < count(); ++i) {
479 if (placesItem(i)->udi() == udi) {
480 removeItem(i);
481 return;
482 }
483 }
484 }
485
486 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error, const QVariant& errorData)
487 {
488 if (error && errorData.isValid()) {
489 emit errorMessage(errorData.toString());
490 }
491 }
492
493 void PlacesItemModel::hideItem()
494 {
495 hideItem(m_hiddenItemToRemove);
496 m_hiddenItemToRemove = -1;
497 }
498
499 void PlacesItemModel::updateBookmarks()
500 {
501 // Verify whether new bookmarks have been added or existing
502 // bookmarks have been changed.
503 KBookmarkGroup root = m_bookmarkManager->root();
504 KBookmark newBookmark = root.first();
505 while (!newBookmark.isNull()) {
506 if (acceptBookmark(newBookmark)) {
507 bool found = false;
508 int modelIndex = 0;
509 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
510 PlacesItem* item = m_bookmarkedItems[i];
511 if (!item) {
512 item = placesItem(modelIndex);
513 ++modelIndex;
514 }
515
516 const KBookmark oldBookmark = item->bookmark();
517 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
518 // The bookmark has been found in the model or as
519 // a hidden item. The content of the bookmark might
520 // have been changed, so an update is done.
521 found = true;
522 if (newBookmark.metaDataItem("UDI").isEmpty()) {
523 item->setBookmark(newBookmark);
524 }
525 break;
526 }
527 }
528
529 if (!found) {
530 PlacesItem* item = new PlacesItem(newBookmark);
531 if (item->isHidden() && !m_hiddenItemsShown) {
532 m_bookmarkedItems.append(item);
533 } else {
534 appendItem(item);
535 }
536 }
537 }
538
539 newBookmark = root.next(newBookmark);
540 }
541
542 // Remove items that are not part of the bookmark-manager anymore
543 int modelIndex = 0;
544 for (int i = m_bookmarkedItems.count() - 1; i >= 0; --i) {
545 PlacesItem* item = m_bookmarkedItems[i];
546 const bool itemIsPartOfModel = (item == 0);
547 if (itemIsPartOfModel) {
548 item = placesItem(modelIndex);
549 }
550
551 bool hasBeenRemoved = true;
552 const KBookmark oldBookmark = item->bookmark();
553 KBookmark newBookmark = root.first();
554 while (!newBookmark.isNull()) {
555 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
556 hasBeenRemoved = false;
557 break;
558 }
559 newBookmark = root.next(newBookmark);
560 }
561
562 if (hasBeenRemoved) {
563 if (m_bookmarkedItems[i]) {
564 delete m_bookmarkedItems[i];
565 m_bookmarkedItems.removeAt(i);
566 } else {
567 removeItem(modelIndex);
568 --modelIndex;
569 }
570 }
571
572 if (itemIsPartOfModel) {
573 ++modelIndex;
574 }
575 }
576 }
577
578 void PlacesItemModel::saveBookmarks()
579 {
580 m_bookmarkManager->emitChanged(m_bookmarkManager->root());
581 }
582
583 void PlacesItemModel::loadBookmarks()
584 {
585 KBookmarkGroup root = m_bookmarkManager->root();
586 KBookmark bookmark = root.first();
587 QSet<QString> devices = m_availableDevices;
588
589 QSet<KUrl> missingSystemBookmarks;
590 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
591 missingSystemBookmarks.insert(data.url);
592 }
593
594 // The bookmarks might have a mixed order of places, devices and search-groups due
595 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
596 // items should always be collected in one group so the items are collected first
597 // in separate lists before inserting them.
598 QList<PlacesItem*> placesItems;
599 QList<PlacesItem*> recentlyAccessedItems;
600 QList<PlacesItem*> searchForItems;
601 QList<PlacesItem*> devicesItems;
602
603 while (!bookmark.isNull()) {
604 const bool deviceAvailable = devices.remove(bookmark.metaDataItem("UDI"));
605 if (acceptBookmark(bookmark)) {
606 PlacesItem* item = new PlacesItem(bookmark);
607 if (deviceAvailable) {
608 devicesItems.append(item);
609 } else {
610 const KUrl url = bookmark.url();
611 if (missingSystemBookmarks.contains(url)) {
612 missingSystemBookmarks.remove(url);
613
614 // Apply the translated text to the system bookmarks, otherwise an outdated
615 // translation might be shown.
616 const int index = m_systemBookmarksIndexes.value(url);
617 item->setText(m_systemBookmarks[index].text);
618 item->setSystemItem(true);
619 }
620
621 switch (item->groupType()) {
622 case PlacesItem::PlacesType: placesItems.append(item); break;
623 case PlacesItem::RecentlyAccessedType: recentlyAccessedItems.append(item); break;
624 case PlacesItem::SearchForType: searchForItems.append(item); break;
625 case PlacesItem::DevicesType:
626 default: Q_ASSERT(false); break;
627 }
628 }
629 }
630
631 bookmark = root.next(bookmark);
632 }
633
634 if (!missingSystemBookmarks.isEmpty()) {
635 // The current bookmarks don't contain all system-bookmarks. Add the missing
636 // bookmarks.
637 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
638 if (missingSystemBookmarks.contains(data.url)) {
639 PlacesItem* item = createSystemPlacesItem(data);
640 switch (item->groupType()) {
641 case PlacesItem::PlacesType: placesItems.append(item); break;
642 case PlacesItem::RecentlyAccessedType: recentlyAccessedItems.append(item); break;
643 case PlacesItem::SearchForType: searchForItems.append(item); break;
644 case PlacesItem::DevicesType:
645 default: Q_ASSERT(false); break;
646 }
647 }
648 }
649 }
650
651 // Create items for devices that have not been stored as bookmark yet
652 foreach (const QString& udi, devices) {
653 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
654 devicesItems.append(new PlacesItem(bookmark));
655 }
656
657 QList<PlacesItem*> items;
658 items.append(placesItems);
659 items.append(recentlyAccessedItems);
660 items.append(searchForItems);
661 items.append(devicesItems);
662
663 foreach (PlacesItem* item, items) {
664 if (!m_hiddenItemsShown && item->isHidden()) {
665 m_bookmarkedItems.append(item);
666 } else {
667 appendItem(item);
668 }
669 }
670
671 #ifdef PLACESITEMMODEL_DEBUG
672 kDebug() << "Loaded bookmarks";
673 showModelState();
674 #endif
675 }
676
677 bool PlacesItemModel::acceptBookmark(const KBookmark& bookmark) const
678 {
679 const QString udi = bookmark.metaDataItem("UDI");
680 const KUrl url = bookmark.url();
681 const QString appName = bookmark.metaDataItem("OnlyInApp");
682 const bool deviceAvailable = m_availableDevices.contains(udi);
683
684 const bool allowedHere = (appName.isEmpty()
685 || appName == KGlobal::mainComponent().componentName()
686 || appName == KGlobal::mainComponent().componentName() + AppNamePrefix)
687 && (m_nepomukRunning || (url.protocol() != QLatin1String("timeline") &&
688 url.protocol() != QLatin1String("search")));
689
690 return (udi.isEmpty() && allowedHere) || deviceAvailable;
691 }
692
693 PlacesItem* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData& data)
694 {
695 KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager,
696 data.text,
697 data.url,
698 data.icon);
699
700 const QString protocol = data.url.protocol();
701 if (protocol == QLatin1String("timeline") || protocol == QLatin1String("search")) {
702 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
703 // for "Recently Accessed" and "Search For" should be a setting available only
704 // in the Places Panel (see description of AppNamePrefix for more details).
705 const QString appName = KGlobal::mainComponent().componentName() + AppNamePrefix;
706 bookmark.setMetaDataItem("OnlyInApp", appName);
707 }
708
709 PlacesItem* item = new PlacesItem(bookmark);
710 item->setSystemItem(true);
711
712 // Create default view-properties for all "Search For" and "Recently Accessed" bookmarks
713 // in case if the user has not already created custom view-properties for a corresponding
714 // query yet.
715 const bool createDefaultViewProperties = (item->groupType() == PlacesItem::SearchForType ||
716 item->groupType() == PlacesItem::RecentlyAccessedType) &&
717 !GeneralSettings::self()->globalViewProps();
718 if (createDefaultViewProperties) {
719 ViewProperties props(convertedUrl(data.url));
720 if (!props.exist()) {
721 const QString path = data.url.path();
722 if (path == QLatin1String("/documents")) {
723 props.setViewMode(DolphinView::DetailsView);
724 props.setPreviewsShown(false);
725 props.setVisibleRoles(QList<QByteArray>() << "text" << "path");
726 } else if (path == QLatin1String("/images")) {
727 props.setViewMode(DolphinView::IconsView);
728 props.setPreviewsShown(true);
729 props.setVisibleRoles(QList<QByteArray>() << "text" << "imageSize");
730 } else if (path == QLatin1String("/audio")) {
731 props.setViewMode(DolphinView::DetailsView);
732 props.setPreviewsShown(false);
733 props.setVisibleRoles(QList<QByteArray>() << "text" << "artist" << "album");
734 } else if (path == QLatin1String("/videos")) {
735 props.setViewMode(DolphinView::IconsView);
736 props.setPreviewsShown(true);
737 props.setVisibleRoles(QList<QByteArray>() << "text");
738 } else if (data.url.protocol() == "timeline") {
739 props.setViewMode(DolphinView::DetailsView);
740 props.setVisibleRoles(QList<QByteArray>() << "text" << "date");
741 }
742 }
743 }
744
745 return item;
746 }
747
748 void PlacesItemModel::createSystemBookmarks()
749 {
750 Q_ASSERT(m_systemBookmarks.isEmpty());
751 Q_ASSERT(m_systemBookmarksIndexes.isEmpty());
752
753 const QString timeLineIcon = "package_utility_time"; // TODO: Ask the Oxygen team to create
754 // a custom icon for the timeline-protocol
755
756 m_systemBookmarks.append(SystemBookmarkData(KUrl(KUser().homeDir()),
757 "user-home",
758 i18nc("@item", "Home")));
759 m_systemBookmarks.append(SystemBookmarkData(KUrl("remote:/"),
760 "network-workgroup",
761 i18nc("@item", "Network")));
762 m_systemBookmarks.append(SystemBookmarkData(KUrl("/"),
763 "folder-red",
764 i18nc("@item", "Root")));
765 m_systemBookmarks.append(SystemBookmarkData(KUrl("trash:/"),
766 "user-trash",
767 i18nc("@item", "Trash")));
768
769 if (m_nepomukRunning) {
770 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/today"),
771 timeLineIcon,
772 i18nc("@item Recently Accessed", "Today")));
773 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/yesterday"),
774 timeLineIcon,
775 i18nc("@item Recently Accessed", "Yesterday")));
776 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/thismonth"),
777 timeLineIcon,
778 i18nc("@item Recently Accessed", "This Month")));
779 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/lastmonth"),
780 timeLineIcon,
781 i18nc("@item Recently Accessed", "Last Month")));
782 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/documents"),
783 "folder-txt",
784 i18nc("@item Commonly Accessed", "Documents")));
785 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/images"),
786 "folder-image",
787 i18nc("@item Commonly Accessed", "Images")));
788 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/audio"),
789 "folder-sound",
790 i18nc("@item Commonly Accessed", "Audio Files")));
791 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/videos"),
792 "folder-video",
793 i18nc("@item Commonly Accessed", "Videos")));
794 }
795
796 for (int i = 0; i < m_systemBookmarks.count(); ++i) {
797 m_systemBookmarksIndexes.insert(m_systemBookmarks[i].url, i);
798 }
799 }
800
801 void PlacesItemModel::initializeAvailableDevices()
802 {
803 m_predicate = Solid::Predicate::fromString(
804 "[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
805 " OR "
806 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
807 " OR "
808 "OpticalDisc.availableContent & 'Audio' ]"
809 " OR "
810 "StorageAccess.ignored == false ]");
811 Q_ASSERT(m_predicate.isValid());
812
813 Solid::DeviceNotifier* notifier = Solid::DeviceNotifier::instance();
814 connect(notifier, SIGNAL(deviceAdded(QString)), this, SLOT(slotDeviceAdded(QString)));
815 connect(notifier, SIGNAL(deviceRemoved(QString)), this, SLOT(slotDeviceRemoved(QString)));
816
817 const QList<Solid::Device>& deviceList = Solid::Device::listFromQuery(m_predicate);
818 foreach(const Solid::Device& device, deviceList) {
819 m_availableDevices << device.udi();
820 }
821 }
822
823 int PlacesItemModel::bookmarkIndex(int index) const
824 {
825 int bookmarkIndex = 0;
826 int modelIndex = 0;
827 while (bookmarkIndex < m_bookmarkedItems.count()) {
828 if (!m_bookmarkedItems[bookmarkIndex]) {
829 if (modelIndex == index) {
830 break;
831 }
832 ++modelIndex;
833 }
834 ++bookmarkIndex;
835 }
836
837 return bookmarkIndex >= m_bookmarkedItems.count() ? -1 : bookmarkIndex;
838 }
839
840 void PlacesItemModel::hideItem(int index)
841 {
842 PlacesItem* shownItem = placesItem(index);
843 if (!shownItem) {
844 return;
845 }
846
847 shownItem->setHidden(true);
848 if (m_hiddenItemsShown) {
849 // Removing items from the model is not allowed if all hidden
850 // items should be shown.
851 return;
852 }
853
854 const int newIndex = bookmarkIndex(index);
855 if (newIndex >= 0) {
856 const KBookmark hiddenBookmark = shownItem->bookmark();
857 PlacesItem* hiddenItem = new PlacesItem(hiddenBookmark);
858
859 const PlacesItem* previousItem = placesItem(index - 1);
860 KBookmark previousBookmark;
861 if (previousItem) {
862 previousBookmark = previousItem->bookmark();
863 }
864
865 const bool updateBookmark = (m_bookmarkManager->root().indexOf(hiddenBookmark) >= 0);
866 removeItem(index);
867
868 if (updateBookmark) {
869 // removeItem() also removed the bookmark from m_bookmarkManager in
870 // PlacesItemModel::onItemRemoved(). However for hidden items the
871 // bookmark should still be remembered, so readd it again:
872 m_bookmarkManager->root().addBookmark(hiddenBookmark);
873 m_bookmarkManager->root().moveBookmark(hiddenBookmark, previousBookmark);
874 triggerBookmarksSaving();
875 }
876
877 m_bookmarkedItems.insert(newIndex, hiddenItem);
878 }
879 }
880
881 void PlacesItemModel::triggerBookmarksSaving()
882 {
883 if (m_saveBookmarksTimer) {
884 m_saveBookmarksTimer->start();
885 }
886 }
887
888 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark& b1, const KBookmark& b2)
889 {
890 const QString udi1 = b1.metaDataItem("UDI");
891 const QString udi2 = b2.metaDataItem("UDI");
892 if (!udi1.isEmpty() && !udi2.isEmpty()) {
893 return udi1 == udi2;
894 } else {
895 return b1.metaDataItem("ID") == b2.metaDataItem("ID");
896 }
897 }
898
899 KUrl PlacesItemModel::createTimelineUrl(const KUrl& url)
900 {
901 // TODO: Clarify with the Nepomuk-team whether it makes sense
902 // provide default-timeline-URLs like 'yesterday', 'this month'
903 // and 'last month'.
904 KUrl timelineUrl;
905
906 const QString path = url.pathOrUrl();
907 if (path.endsWith("yesterday")) {
908 const QDate date = QDate::currentDate().addDays(-1);
909 const int year = date.year();
910 const int month = date.month();
911 const int day = date.day();
912 timelineUrl = "timeline:/" + timelineDateString(year, month) +
913 '/' + timelineDateString(year, month, day);
914 } else if (path.endsWith("thismonth")) {
915 const QDate date = QDate::currentDate();
916 timelineUrl = "timeline:/" + timelineDateString(date.year(), date.month());
917 } else if (path.endsWith("lastmonth")) {
918 const QDate date = QDate::currentDate().addMonths(-1);
919 timelineUrl = "timeline:/" + timelineDateString(date.year(), date.month());
920 } else {
921 Q_ASSERT(path.endsWith("today"));
922 timelineUrl= url;
923 }
924
925 return timelineUrl;
926 }
927
928 QString PlacesItemModel::timelineDateString(int year, int month, int day)
929 {
930 QString date = QString::number(year) + '-';
931 if (month < 10) {
932 date += '0';
933 }
934 date += QString::number(month);
935
936 if (day >= 1) {
937 date += '-';
938 if (day < 10) {
939 date += '0';
940 }
941 date += QString::number(day);
942 }
943
944 return date;
945 }
946
947 KUrl PlacesItemModel::createSearchUrl(const KUrl& url)
948 {
949 KUrl searchUrl;
950
951 #ifdef HAVE_NEPOMUK
952 const QString path = url.pathOrUrl();
953 if (path.endsWith("documents")) {
954 searchUrl = searchUrlForTerm(Nepomuk::Query::ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Document()));
955 } else if (path.endsWith("images")) {
956 searchUrl = searchUrlForTerm(Nepomuk::Query::ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Image()));
957 } else if (path.endsWith("audio")) {
958 searchUrl = searchUrlForTerm(Nepomuk::Query::ComparisonTerm(Nepomuk::Vocabulary::NIE::mimeType(),
959 Nepomuk::Query::LiteralTerm("audio")));
960 } else if (path.endsWith("videos")) {
961 searchUrl = searchUrlForTerm(Nepomuk::Query::ComparisonTerm(Nepomuk::Vocabulary::NIE::mimeType(),
962 Nepomuk::Query::LiteralTerm("video")));
963 } else {
964 Q_ASSERT(false);
965 }
966 #else
967 Q_UNUSED(url);
968 #endif
969
970 return searchUrl;
971 }
972
973 #ifdef HAVE_NEPOMUK
974 KUrl PlacesItemModel::searchUrlForTerm(const Nepomuk::Query::Term& term)
975 {
976 const Nepomuk::Query::Query query(term);
977 return query.toSearchUrl();
978 }
979 #endif
980
981 #ifdef PLACESITEMMODEL_DEBUG
982 void PlacesItemModel::showModelState()
983 {
984 kDebug() << "=================================";
985 kDebug() << "Model:";
986 kDebug() << "hidden-index model-index text";
987 int modelIndex = 0;
988 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
989 if (m_bookmarkedItems[i]) {
990 kDebug() << i << "(Hidden) " << " " << m_bookmarkedItems[i]->dataValue("text").toString();
991 } else {
992 if (item(modelIndex)) {
993 kDebug() << i << " " << modelIndex << " " << item(modelIndex)->dataValue("text").toString();
994 } else {
995 kDebug() << i << " " << modelIndex << " " << "(not available yet)";
996 }
997 ++modelIndex;
998 }
999 }
1000
1001 kDebug();
1002 kDebug() << "Bookmarks:";
1003
1004 int bookmarkIndex = 0;
1005 KBookmarkGroup root = m_bookmarkManager->root();
1006 KBookmark bookmark = root.first();
1007 while (!bookmark.isNull()) {
1008 const QString udi = bookmark.metaDataItem("UDI");
1009 const QString text = udi.isEmpty() ? bookmark.text() : udi;
1010 if (bookmark.metaDataItem("IsHidden") == QLatin1String("true")) {
1011 kDebug() << bookmarkIndex << "(Hidden)" << text;
1012 } else {
1013 kDebug() << bookmarkIndex << " " << text;
1014 }
1015
1016 bookmark = root.next(bookmark);
1017 ++bookmarkIndex;
1018 }
1019 }
1020 #endif
1021
1022 #include "placesitemmodel.moc"