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