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