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