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