]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/places/placesitemmodel.cpp
Places Panel: Prepare code to save state of bookmarks
[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 <KBookmark>
27 #include <KBookmarkGroup>
28 #include <KBookmarkManager>
29 #include <KComponentData>
30 #include <KDebug>
31 #include <KIcon>
32 #include <KLocale>
33 #include <KStandardDirs>
34 #include <KUser>
35 #include "placesitem.h"
36 #include <QAction>
37 #include <QDate>
38
39 #include <Solid/Device>
40 #include <Solid/DeviceNotifier>
41 #include <Solid/OpticalDisc>
42 #include <Solid/OpticalDrive>
43 #include <Solid/StorageAccess>
44 #include <Solid/StorageDrive>
45
46 #ifdef HAVE_NEPOMUK
47 #include <Nepomuk/ResourceManager>
48 #endif
49
50 PlacesItemModel::PlacesItemModel(QObject* parent) :
51 KStandardItemModel(parent),
52 m_nepomukRunning(false),
53 m_hiddenItemsShown(false),
54 m_availableDevices(),
55 m_predicate(),
56 m_bookmarkManager(0),
57 m_systemBookmarks(),
58 m_systemBookmarksIndexes(),
59 m_hiddenItems()
60 {
61 #ifdef HAVE_NEPOMUK
62 m_nepomukRunning = (Nepomuk::ResourceManager::instance()->initialized());
63 #endif
64 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
65 m_bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
66
67 createSystemBookmarks();
68 initializeAvailableDevices();
69 loadBookmarks();
70 }
71
72 PlacesItemModel::~PlacesItemModel()
73 {
74 qDeleteAll(m_hiddenItems);
75 m_hiddenItems.clear();
76 }
77
78 PlacesItem* PlacesItemModel::placesItem(int index) const
79 {
80 return dynamic_cast<PlacesItem*>(item(index));
81 }
82
83 int PlacesItemModel::hiddenCount() const
84 {
85 int modelIndex = 0;
86 int itemCount = 0;
87 foreach (const PlacesItem* hiddenItem, m_hiddenItems) {
88 if (hiddenItem) {
89 ++itemCount;
90 } else {
91 if (placesItem(modelIndex)->isHidden()) {
92 ++itemCount;
93 }
94 ++modelIndex;
95 }
96 }
97
98 return itemCount;
99 }
100
101 void PlacesItemModel::setItemHidden(int index, bool hide)
102 {
103 if (index >= 0 && index < count()) {
104 PlacesItem* shownItem = placesItem(index);
105 shownItem->setHidden(true);
106 if (!m_hiddenItemsShown && hide) {
107 const int newIndex = hiddenIndex(index);
108 PlacesItem* hiddenItem = new PlacesItem(*shownItem);
109 removeItem(index);
110 m_hiddenItems.insert(newIndex, hiddenItem);
111 }
112 #ifdef PLACESITEMMODEL_DEBUG
113 kDebug() << "Changed hide-state from" << index << "to" << hide;
114 showModelState();
115 #endif
116 }
117 }
118
119 bool PlacesItemModel::isItemHidden(int index) const
120 {
121 return (index >= 0 && index < count()) ? m_hiddenItems[index] != 0 : false;
122 }
123
124 void PlacesItemModel::setHiddenItemsShown(bool show)
125 {
126 if (m_hiddenItemsShown == show) {
127 return;
128 }
129
130 m_hiddenItemsShown = show;
131
132 if (show) {
133 // Move all items that are part of m_hiddenItems to the model.
134 int modelIndex = 0;
135 for (int hiddenIndex = 0; hiddenIndex < m_hiddenItems.count(); ++hiddenIndex) {
136 if (m_hiddenItems[hiddenIndex]) {
137 PlacesItem* visibleItem = new PlacesItem(*m_hiddenItems[hiddenIndex]);
138 delete m_hiddenItems[hiddenIndex];
139 m_hiddenItems.removeAt(hiddenIndex);
140 insertItem(modelIndex, visibleItem);
141 Q_ASSERT(!m_hiddenItems[hiddenIndex]);
142 }
143 ++modelIndex;
144 }
145 } else {
146 // Move all items of the model, where the "isHidden" property is true, to
147 // m_hiddenItems.
148 Q_ASSERT(m_hiddenItems.count() == count());
149 for (int i = count() - 1; i >= 0; --i) {
150 PlacesItem* visibleItem = placesItem(i);
151 if (visibleItem->isHidden()) {
152 PlacesItem* hiddenItem = new PlacesItem(*visibleItem);
153 removeItem(i);
154 m_hiddenItems.insert(i, hiddenItem);
155 }
156 }
157 }
158 #ifdef PLACESITEMMODEL_DEBUG
159 kDebug() << "Changed visibility of hidden items";
160 showModelState();
161 #endif
162 }
163
164 bool PlacesItemModel::hiddenItemsShown() const
165 {
166 return m_hiddenItemsShown;
167 }
168
169 int PlacesItemModel::closestItem(const KUrl& url) const
170 {
171 int foundIndex = -1;
172 int maxLength = 0;
173
174 for (int i = 0; i < count(); ++i) {
175 const KUrl itemUrl = placesItem(i)->url();
176 if (itemUrl.isParentOf(url)) {
177 const int length = itemUrl.prettyUrl().length();
178 if (length > maxLength) {
179 foundIndex = i;
180 maxLength = length;
181 }
182 }
183 }
184
185 return foundIndex;
186 }
187
188 QString PlacesItemModel::groupName(const KUrl &url) const
189 {
190 const QString protocol = url.protocol();
191
192 if (protocol.contains(QLatin1String("search"))) {
193 return searchForGroupName();
194 }
195
196 if (protocol == QLatin1String("timeline")) {
197 return recentlyAccessedGroupName();
198 }
199
200 return placesGroupName();
201 }
202
203 QAction* PlacesItemModel::ejectAction(int index) const
204 {
205 const PlacesItem* item = placesItem(index);
206 if (item && item->device().is<Solid::OpticalDisc>()) {
207 return new QAction(KIcon("media-eject"), i18nc("@item", "Eject '%1'", item->text()), 0);
208 }
209
210 return 0;
211 }
212
213 QAction* PlacesItemModel::teardownAction(int index) const
214 {
215 const PlacesItem* item = placesItem(index);
216 if (!item) {
217 return 0;
218 }
219
220 Solid::Device device = item->device();
221 const bool providesTearDown = device.is<Solid::StorageAccess>() &&
222 device.as<Solid::StorageAccess>()->isAccessible();
223 if (!providesTearDown) {
224 return 0;
225 }
226
227 Solid::StorageDrive* drive = device.as<Solid::StorageDrive>();
228 if (!drive) {
229 drive = device.parent().as<Solid::StorageDrive>();
230 }
231
232 bool hotPluggable = false;
233 bool removable = false;
234 if (drive) {
235 hotPluggable = drive->isHotpluggable();
236 removable = drive->isRemovable();
237 }
238
239 QString iconName;
240 QString text;
241 const QString label = item->text();
242 if (device.is<Solid::OpticalDisc>()) {
243 text = i18nc("@item", "Release '%1'", label);
244 } else if (removable || hotPluggable) {
245 text = i18nc("@item", "Safely Remove '%1'", label);
246 iconName = "media-eject";
247 } else {
248 text = i18nc("@item", "Unmount '%1'", label);
249 iconName = "media-eject";
250 }
251
252 if (iconName.isEmpty()) {
253 return new QAction(text, 0);
254 }
255
256 return new QAction(KIcon(iconName), text, 0);
257 }
258
259 void PlacesItemModel::requestEject(int index)
260 {
261 const PlacesItem* item = placesItem(index);
262 if (item) {
263 Solid::OpticalDrive* drive = item->device().parent().as<Solid::OpticalDrive>();
264 if (drive) {
265 connect(drive, SIGNAL(ejectDone(Solid::ErrorType,QVariant,QString)),
266 this, SLOT(slotStorageTeardownDone(Solid::ErrorType,QVariant)));
267 drive->eject();
268 } else {
269
270 }
271 }
272 }
273
274 void PlacesItemModel::requestTeardown(int index)
275 {
276 const PlacesItem* item = placesItem(index);
277 if (item) {
278 Solid::StorageAccess* access = item->device().as<Solid::StorageAccess>();
279 if (access) {
280 connect(access, SIGNAL(teardownDone(Solid::ErrorType,QVariant,QString)),
281 this, SLOT(slotStorageTeardownDone(Solid::ErrorType,QVariant)));
282 access->teardown();
283 } else {
284 const QString label = item->text();
285 const QString message = i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label);
286 emit errorMessage(message);
287 }
288 }
289 }
290
291
292 void PlacesItemModel::save()
293 {
294 // TODO: Temporary deactivated until 100 % backward compatibility is provided
295 // m_bookmarkManager->emitChanged(m_bookmarkManager->root());
296 }
297
298 void PlacesItemModel::onItemInserted(int index)
299 {
300 if (index == count() - 1) {
301 // The item has been appended as last item to the list. In this
302 // case assure that it is also appended after the hidden items and
303 // not before (like done otherwise).
304 m_hiddenItems.append(0);
305 return;
306 }
307
308 int modelIndex = 0;
309 int hiddenIndex = 0;
310 while (hiddenIndex < m_hiddenItems.count()) {
311 if (!m_hiddenItems[hiddenIndex]) {
312 ++modelIndex;
313 if (modelIndex + 1 == index) {
314 ++hiddenIndex;
315 break;
316 }
317 }
318 ++hiddenIndex;
319 }
320 m_hiddenItems.insert(hiddenIndex, 0);
321
322 #ifdef PLACESITEMMODEL_DEBUG
323 kDebug() << "Inserted item" << index;
324 showModelState();
325 #endif
326 }
327
328 void PlacesItemModel::onItemRemoved(int index)
329 {
330 const int removeIndex = hiddenIndex(index);
331 Q_ASSERT(!m_hiddenItems[removeIndex]);
332 m_hiddenItems.removeAt(removeIndex);
333 #ifdef PLACESITEMMODEL_DEBUG
334 kDebug() << "Removed item" << index;
335 showModelState();
336 #endif
337 }
338
339 void PlacesItemModel::onItemReplaced(int index)
340 {
341 Q_UNUSED(index);
342 }
343
344 void PlacesItemModel::slotDeviceAdded(const QString& udi)
345 {
346 const Solid::Device device(udi);
347 if (m_predicate.matches(device)) {
348 m_availableDevices << udi;
349 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
350 appendItem(new PlacesItem(bookmark));
351 }
352 }
353
354 void PlacesItemModel::slotDeviceRemoved(const QString& udi)
355 {
356 if (!m_availableDevices.contains(udi)) {
357 return;
358 }
359
360 for (int i = 0; i < m_hiddenItems.count(); ++i) {
361 PlacesItem* item = m_hiddenItems[i];
362 if (item && item->udi() == udi) {
363 m_hiddenItems.removeAt(i);
364 delete item;
365 return;
366 }
367 }
368
369 for (int i = 0; i < count(); ++i) {
370 if (placesItem(i)->udi() == udi) {
371 removeItem(i);
372 return;
373 }
374 }
375 }
376
377 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error, const QVariant& errorData)
378 {
379 if (error && errorData.isValid()) {
380 emit errorMessage(errorData.toString());
381 }
382 }
383
384 void PlacesItemModel::loadBookmarks()
385 {
386 KBookmarkGroup root = m_bookmarkManager->root();
387 KBookmark bookmark = root.first();
388 QSet<QString> devices = m_availableDevices;
389
390 QSet<KUrl> missingSystemBookmarks;
391 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
392 missingSystemBookmarks.insert(data.url);
393 }
394
395 // The bookmarks might have a mixed order of "places" and "devices". In
396 // Dolphin's places panel the devices should always be appended as last
397 // group, so they are collected as separate lists.
398 QList<PlacesItem*> placesItems;
399 QList<PlacesItem*> devicesItems;
400
401 while (!bookmark.isNull()) {
402 const QString udi = bookmark.metaDataItem("UDI");
403 const KUrl url = bookmark.url();
404 const QString appName = bookmark.metaDataItem("OnlyInApp");
405 const bool deviceAvailable = devices.remove(udi);
406
407 const bool allowedHere = (appName.isEmpty() || appName == KGlobal::mainComponent().componentName())
408 && (m_nepomukRunning || (url.protocol() != QLatin1String("timeline") &&
409 url.protocol() != QLatin1String("search")));
410
411 if ((udi.isEmpty() && allowedHere) || deviceAvailable) {
412 PlacesItem* item = new PlacesItem(bookmark);
413 if (deviceAvailable) {
414 devicesItems.append(item);
415 } else {
416 placesItems.append(item);
417
418 if (missingSystemBookmarks.contains(url)) {
419 missingSystemBookmarks.remove(url);
420
421 // Apply the translated text to the system bookmarks, otherwise an outdated
422 // translation might be shown.
423 const int index = m_systemBookmarksIndexes.value(url);
424 item->setText(m_systemBookmarks[index].text);
425 item->setSystemItem(true);
426 item->setGroup(m_systemBookmarks[index].group);
427 }
428 }
429 }
430
431 bookmark = root.next(bookmark);
432 }
433
434 addItems(placesItems);
435
436 if (!missingSystemBookmarks.isEmpty()) {
437 // The current bookmarks don't contain all system-bookmarks. Add the missing
438 // bookmarks.
439 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
440 if (missingSystemBookmarks.contains(data.url)) {
441 KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager,
442 data.text,
443 data.url,
444 data.icon);
445
446 const QString protocol = data.url.protocol();
447 if (protocol == QLatin1String("timeline") || protocol == QLatin1String("search")) {
448 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
449 // for timeline and search should be a Dolphin-specific setting.
450 bookmark.setMetaDataItem("OnlyInApp", KGlobal::mainComponent().componentName());
451 }
452
453 PlacesItem* item = new PlacesItem(bookmark);
454 item->setSystemItem(true);
455 item->setGroup(data.group);
456 appendItem(item);
457 }
458 }
459 }
460
461 // Create items for devices that have not stored as bookmark yet
462 foreach (const QString& udi, devices) {
463 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
464 devicesItems.append(new PlacesItem(bookmark));
465 }
466
467 addItems(devicesItems);
468
469 #ifdef PLACESITEMMODEL_DEBUG
470 kDebug() << "Loaded bookmarks";
471 showModelState();
472 #endif
473 }
474
475 void PlacesItemModel::addItems(const QList<PlacesItem*>& items)
476 {
477 foreach (PlacesItem* item, items) {
478 if (!m_hiddenItemsShown && item->isHidden()) {
479 m_hiddenItems.append(item);
480 } else {
481 appendItem(item);
482 }
483 }
484 }
485
486 void PlacesItemModel::createSystemBookmarks()
487 {
488 Q_ASSERT(m_systemBookmarks.isEmpty());
489 Q_ASSERT(m_systemBookmarksIndexes.isEmpty());
490
491 const QString placesGroup = placesGroupName();
492 const QString recentlyAccessedGroup = recentlyAccessedGroupName();
493 const QString searchForGroup = searchForGroupName();
494 const QString timeLineIcon = "package_utility_time"; // TODO: Ask the Oxygen team to create
495 // a custom icon for the timeline-protocol
496
497 m_systemBookmarks.append(SystemBookmarkData(KUrl(KUser().homeDir()),
498 "user-home",
499 i18nc("@item", "Home"),
500 placesGroup));
501 m_systemBookmarks.append(SystemBookmarkData(KUrl("remote:/"),
502 "network-workgroup",
503 i18nc("@item", "Network"),
504 placesGroup));
505 m_systemBookmarks.append(SystemBookmarkData(KUrl("/"),
506 "folder-red",
507 i18nc("@item", "Root"),
508 placesGroup));
509 m_systemBookmarks.append(SystemBookmarkData(KUrl("trash:/"),
510 "user-trash",
511 i18nc("@item", "Trash"),
512 placesGroup));
513
514 if (m_nepomukRunning) {
515 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/today"),
516 timeLineIcon,
517 i18nc("@item Recently Accessed", "Today"),
518 recentlyAccessedGroup));
519 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/yesterday"),
520 timeLineIcon,
521 i18nc("@item Recently Accessed", "Yesterday"),
522 recentlyAccessedGroup));
523 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/thismonth"),
524 timeLineIcon,
525 i18nc("@item Recently Accessed", "This Month"),
526 recentlyAccessedGroup));
527 m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/lastmonth"),
528 timeLineIcon,
529 i18nc("@item Recently Accessed", "Last Month"),
530 recentlyAccessedGroup));
531 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/documents"),
532 "folder-txt",
533 i18nc("@item Commonly Accessed", "Documents"),
534 searchForGroup));
535 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/images"),
536 "folder-image",
537 i18nc("@item Commonly Accessed", "Images"),
538 searchForGroup));
539 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/audio"),
540 "folder-sound",
541 i18nc("@item Commonly Accessed", "Audio"),
542 searchForGroup));
543 m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/videos"),
544 "folder-video",
545 i18nc("@item Commonly Accessed", "Videos"),
546 searchForGroup));
547 }
548
549 for (int i = 0; i < m_systemBookmarks.count(); ++i) {
550 m_systemBookmarksIndexes.insert(m_systemBookmarks[i].url, i);
551 }
552 }
553
554 void PlacesItemModel::initializeAvailableDevices()
555 {
556 m_predicate = Solid::Predicate::fromString(
557 "[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
558 " OR "
559 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
560 " OR "
561 "OpticalDisc.availableContent & 'Audio' ]"
562 " OR "
563 "StorageAccess.ignored == false ]");
564 Q_ASSERT(m_predicate.isValid());
565
566 Solid::DeviceNotifier* notifier = Solid::DeviceNotifier::instance();
567 connect(notifier, SIGNAL(deviceAdded(QString)), this, SLOT(slotDeviceAdded(QString)));
568 connect(notifier, SIGNAL(deviceRemoved(QString)), this, SLOT(slotDeviceRemoved(QString)));
569
570 const QList<Solid::Device>& deviceList = Solid::Device::listFromQuery(m_predicate);
571 foreach(const Solid::Device& device, deviceList) {
572 m_availableDevices << device.udi();
573 }
574 }
575
576 int PlacesItemModel::hiddenIndex(int index) const
577 {
578 int hiddenIndex = 0;
579 int visibleItemIndex = 0;
580 while (hiddenIndex < m_hiddenItems.count()) {
581 if (!m_hiddenItems[hiddenIndex]) {
582 if (visibleItemIndex == index) {
583 break;
584 }
585 ++visibleItemIndex;
586 }
587 ++hiddenIndex;
588 }
589
590 return hiddenIndex >= m_hiddenItems.count() ? -1 : hiddenIndex;
591 }
592
593 QString PlacesItemModel::placesGroupName()
594 {
595 return i18nc("@item", "Places");
596 }
597
598 QString PlacesItemModel::recentlyAccessedGroupName()
599 {
600 return i18nc("@item", "Recently Accessed");
601 }
602
603 QString PlacesItemModel::searchForGroupName()
604 {
605 return i18nc("@item", "Search For");
606 }
607
608 #ifdef PLACESITEMMODEL_DEBUG
609 void PlacesItemModel::showModelState()
610 {
611 kDebug() << "hidden-index model-index text";
612 int j = 0;
613 for (int i = 0; i < m_hiddenItems.count(); ++i) {
614 if (m_hiddenItems[i]) {
615 kDebug() << i << "(Hidden) " << " " << m_hiddenItems[i]->dataValue("text").toString();
616 } else {
617 kDebug() << i << " " << j << " " << item(j)->dataValue("text").toString();
618 ++j;
619 }
620 }
621 }
622 #endif
623
624 #include "placesitemmodel.moc"