┌   ┐
54
└   ┘

summaryrefslogtreecommitdiff
path: root/src/panels/places/placesitemmodel.cpp
blob: 7bbd651815095fb76a29832855c1c2579afad1ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
/***************************************************************************
 *   Copyright (C) 2012 by Peter Penz <[email protected]>             *
 *                                                                         *
 *   Based on KFilePlacesModel from kdelibs:                               *
 *   Copyright (C) 2007 Kevin Ottens <[email protected]>                       *
 *   Copyright (C) 2007 David Faure <[email protected]>                        *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA            *
 ***************************************************************************/

#include "placesitemmodel.h"

#include <KBookmark>
#include <KBookmarkGroup>
#include <KBookmarkManager>
#include <KComponentData>
#include <KDebug>
#include <KIcon>
#include <KLocale>
#include <KStandardDirs>
#include <KUser>
#include "placesitem.h"
#include <QAction>
#include <QDate>
#include <QTimer>

#include <Solid/Device>
#include <Solid/DeviceNotifier>
#include <Solid/OpticalDisc>
#include <Solid/OpticalDrive>
#include <Solid/StorageAccess>
#include <Solid/StorageDrive>

#ifdef HAVE_NEPOMUK
    #include <Nepomuk/ResourceManager>
#endif

PlacesItemModel::PlacesItemModel(QObject* parent) :
    KStandardItemModel(parent),
    m_nepomukRunning(false),
    m_hiddenItemsShown(false),
    m_availableDevices(),
    m_predicate(),
    m_bookmarkManager(0),
    m_systemBookmarks(),
    m_systemBookmarksIndexes(),
    m_hiddenItems(),
    m_hiddenItemToRemove(-1),
    m_saveBookmarksTimer(0)
{
#ifdef HAVE_NEPOMUK
    m_nepomukRunning = (Nepomuk::ResourceManager::instance()->initialized());
#endif
    const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
    m_bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");

    createSystemBookmarks();
    initializeAvailableDevices();
    loadBookmarks();

    m_saveBookmarksTimer = new QTimer(this);
    m_saveBookmarksTimer->setInterval(100);
    m_saveBookmarksTimer->setSingleShot(true);
    connect(m_saveBookmarksTimer, SIGNAL(timeout()), this, SLOT(saveBookmarks()));
}

PlacesItemModel::~PlacesItemModel()
{
    saveBookmarks();
    qDeleteAll(m_hiddenItems);
    m_hiddenItems.clear();
}

PlacesItem* PlacesItemModel::placesItem(int index) const
{
    return dynamic_cast<PlacesItem*>(item(index));
}

int PlacesItemModel::hiddenCount() const
{
    int modelIndex = 0;
    int itemCount = 0;
    foreach (const PlacesItem* hiddenItem, m_hiddenItems) {
        if (hiddenItem) {
            ++itemCount;
        } else {
            if (placesItem(modelIndex)->isHidden()) {
                ++itemCount;
            }
            ++modelIndex;
        }
    }

    return itemCount;
}

void PlacesItemModel::setHiddenItemsShown(bool show)
{
    if (m_hiddenItemsShown == show) {
        return;
    }

    m_hiddenItemsShown = show;

    if (show) {
        // Move all items that are part of m_hiddenItems to the model.
        int modelIndex = 0;
        for (int hiddenIndex = 0; hiddenIndex < m_hiddenItems.count(); ++hiddenIndex) {
            if (m_hiddenItems[hiddenIndex]) {
                PlacesItem* visibleItem = new PlacesItem(*m_hiddenItems[hiddenIndex]);
                delete m_hiddenItems[hiddenIndex];
                m_hiddenItems.removeAt(hiddenIndex);
                insertItem(modelIndex, visibleItem);
                Q_ASSERT(!m_hiddenItems[hiddenIndex]);
            }
            ++modelIndex;
        }
    } else {
        // Move all items of the model, where the "isHidden" property is true, to
        // m_hiddenItems.
        Q_ASSERT(m_hiddenItems.count() == count());
        for (int i = count() - 1; i >= 0; --i) {
            PlacesItem* visibleItem = placesItem(i);
            if (visibleItem->isHidden()) {
                PlacesItem* hiddenItem = new PlacesItem(*visibleItem);
                removeItem(i);
                m_hiddenItems.insert(i, hiddenItem);
            }
        }
    }
#ifdef PLACESITEMMODEL_DEBUG
        kDebug() << "Changed visibility of hidden items";
        showModelState();
#endif
}

bool PlacesItemModel::hiddenItemsShown() const
{
    return m_hiddenItemsShown;
}

int PlacesItemModel::closestItem(const KUrl& url) const
{
    int foundIndex = -1;
    int maxLength = 0;

    for (int i = 0; i < count(); ++i) {
        const KUrl itemUrl = placesItem(i)->url();
        if (itemUrl.isParentOf(url)) {
            const int length = itemUrl.prettyUrl().length();
            if (length > maxLength) {
                foundIndex = i;
                maxLength = length;
            }
        }
    }

    return foundIndex;
}

QString PlacesItemModel::groupName(const KUrl &url) const
{
    const QString protocol = url.protocol();

    if (protocol.contains(QLatin1String("search"))) {
        return searchForGroupName();
    }

    if (protocol == QLatin1String("timeline")) {
        return recentlyAccessedGroupName();
    }

    return placesGroupName();
}

QAction* PlacesItemModel::ejectAction(int index) const
{
    const PlacesItem* item = placesItem(index);
    if (item && item->device().is<Solid::OpticalDisc>()) {
        return new QAction(KIcon("media-eject"), i18nc("@item", "Eject '%1'", item->text()), 0);
    }

    return 0;
}

QAction* PlacesItemModel::teardownAction(int index) const
{
    const PlacesItem* item = placesItem(index);
    if (!item) {
        return 0;
    }

    Solid::Device device = item->device();
    const bool providesTearDown = device.is<Solid::StorageAccess>() &&
                                  device.as<Solid::StorageAccess>()->isAccessible();
    if (!providesTearDown) {
        return 0;
    }

    Solid::StorageDrive* drive = device.as<Solid::StorageDrive>();
    if (!drive) {
        drive = device.parent().as<Solid::StorageDrive>();
    }

    bool hotPluggable = false;
    bool removable = false;
    if (drive) {
        hotPluggable = drive->isHotpluggable();
        removable = drive->isRemovable();
    }

    QString iconName;
    QString text;
    const QString label = item->text();
    if (device.is<Solid::OpticalDisc>()) {
        text = i18nc("@item", "Release '%1'", label);
    } else if (removable || hotPluggable) {
        text = i18nc("@item", "Safely Remove '%1'", label);
        iconName = "media-eject";
    } else {
        text = i18nc("@item", "Unmount '%1'", label);
        iconName = "media-eject";
    }

    if (iconName.isEmpty()) {
        return new QAction(text, 0);
    }

    return new QAction(KIcon(iconName), text, 0);
}

void PlacesItemModel::requestEject(int index)
{
    const PlacesItem* item = placesItem(index);
    if (item) {
        Solid::OpticalDrive* drive = item->device().parent().as<Solid::OpticalDrive>();
        if (drive) {
            connect(drive, SIGNAL(ejectDone(Solid::ErrorType,QVariant,QString)),
                    this, SLOT(slotStorageTeardownDone(Solid::ErrorType,QVariant)));
            drive->eject();
        } else {

        }
    }
}

void PlacesItemModel::requestTeardown(int index)
{
    const PlacesItem* item = placesItem(index);
    if (item) {
        Solid::StorageAccess* access = item->device().as<Solid::StorageAccess>();
        if (access) {
            connect(access, SIGNAL(teardownDone(Solid::ErrorType,QVariant,QString)),
                    this, SLOT(slotStorageTeardownDone(Solid::ErrorType,QVariant)));
            access->teardown();
        } else {
            const QString label = item->text();
            const QString message = i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label);
            emit errorMessage(message);
        }
    }
}

void PlacesItemModel::onItemInserted(int index)
{
    if (index == count() - 1) {
        // The item has been appended as last item to the list. In this
        // case assure that it is also appended after the hidden items and
        // not before (like done otherwise).
        m_hiddenItems.append(0);
        return;
    }

    int modelIndex = -1;
    int hiddenIndex = 0;
    while (hiddenIndex < m_hiddenItems.count()) {
        if (!m_hiddenItems[hiddenIndex]) {
            ++modelIndex;
            if (modelIndex + 1 == index) {
                break;
            }
        }
        ++hiddenIndex;
    }
    m_hiddenItems.insert(hiddenIndex, 0);

    m_saveBookmarksTimer->start();

#ifdef PLACESITEMMODEL_DEBUG
    kDebug() << "Inserted item" << index;
    showModelState();
#endif
}

void PlacesItemModel::onItemRemoved(int index)
{
    const int removeIndex = hiddenIndex(index);
    Q_ASSERT(!m_hiddenItems[removeIndex]);
    m_hiddenItems.removeAt(removeIndex);

    m_saveBookmarksTimer->start();

#ifdef PLACESITEMMODEL_DEBUG
    kDebug() << "Removed item" << index;
    showModelState();
#endif
}

void PlacesItemModel::onItemChanged(int index, const QSet<QByteArray>& changedRoles)
{
    if (changedRoles.contains("isHidden")) {
        const PlacesItem* shownItem = placesItem(index);
        Q_ASSERT(shownItem);
        if (!m_hiddenItemsShown && shownItem->isHidden()) {
            m_hiddenItemToRemove = index;
            QTimer::singleShot(0, this, SLOT(removeHiddenItem()));
        }
    }
    m_saveBookmarksTimer->start();
}

void PlacesItemModel::slotDeviceAdded(const QString& udi)
{
    const Solid::Device device(udi);
    if (m_predicate.matches(device)) {
        m_availableDevices << udi;
        const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
        appendItem(new PlacesItem(bookmark));
    }
}

void PlacesItemModel::slotDeviceRemoved(const QString& udi)
{
    if (!m_availableDevices.contains(udi)) {
        return;
    }

    for (int i = 0; i < m_hiddenItems.count(); ++i) {
        PlacesItem* item = m_hiddenItems[i];
        if (item && item->udi() == udi) {
            m_hiddenItems.removeAt(i);
            delete item;
            return;
        }
     }

     for (int i = 0; i < count(); ++i) {
         if (placesItem(i)->udi() == udi) {
             removeItem(i);
             return;
         }
     }
}

void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error, const QVariant& errorData)
{
    if (error && errorData.isValid()) {
        emit errorMessage(errorData.toString());
    }
}

void PlacesItemModel::removeHiddenItem()
{
    const PlacesItem* shownItem = placesItem(m_hiddenItemToRemove);
    const int newIndex = hiddenIndex(m_hiddenItemToRemove);
    if (shownItem && newIndex >= 0) {
        PlacesItem* hiddenItem = new PlacesItem(*shownItem);
        removeItem(m_hiddenItemToRemove);
        m_hiddenItems.insert(newIndex, hiddenItem);
        m_saveBookmarksTimer->start();
    }
    m_hiddenItemToRemove = -1;
}


void PlacesItemModel::saveBookmarks()
{
    // TODO: Temporary deactivated until 100 % backward compatibility is provided
    // m_bookmarkManager->emitChanged(m_bookmarkManager->root());
}

void PlacesItemModel::loadBookmarks()
{
    KBookmarkGroup root = m_bookmarkManager->root();
    KBookmark bookmark = root.first();
    QSet<QString> devices = m_availableDevices;

    QSet<KUrl> missingSystemBookmarks;
    foreach (const SystemBookmarkData& data, m_systemBookmarks) {
        missingSystemBookmarks.insert(data.url);
    }

    // The bookmarks might have a mixed order of "places" and "devices". In
    // Dolphin's places panel the devices should always be appended as last
    // group, so they are collected as separate lists.
    QList<PlacesItem*> placesItems;
    QList<PlacesItem*> devicesItems;

    while (!bookmark.isNull()) {
        const QString udi = bookmark.metaDataItem("UDI");
        const KUrl url = bookmark.url();
        const QString appName = bookmark.metaDataItem("OnlyInApp");
        const bool deviceAvailable = devices.remove(udi);

        const bool allowedHere = (appName.isEmpty() || appName == KGlobal::mainComponent().componentName())
                                 && (m_nepomukRunning || (url.protocol() != QLatin1String("timeline") &&
                                                          url.protocol() != QLatin1String("search")));

        if ((udi.isEmpty() && allowedHere) || deviceAvailable) {
            PlacesItem* item = new PlacesItem(bookmark);
            if (deviceAvailable) {
                devicesItems.append(item);
            } else {
                placesItems.append(item);

                if (missingSystemBookmarks.contains(url)) {
                    missingSystemBookmarks.remove(url);

                    // Apply the translated text to the system bookmarks, otherwise an outdated
                    // translation might be shown.
                    const int index = m_systemBookmarksIndexes.value(url);
                    item->setText(m_systemBookmarks[index].text);
                    item->setSystemItem(true);
                    item->setGroup(m_systemBookmarks[index].group);
                }
            }
        }

        bookmark = root.next(bookmark);
    }

    addItems(placesItems);

    if (!missingSystemBookmarks.isEmpty()) {
        // The current bookmarks don't contain all system-bookmarks. Add the missing
        // bookmarks.
        foreach (const SystemBookmarkData& data, m_systemBookmarks) {
            if (missingSystemBookmarks.contains(data.url)) {
                KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager,
                                                                data.text,
                                                                data.url,
                                                                data.icon);

                const QString protocol = data.url.protocol();
                if (protocol == QLatin1String("timeline") || protocol == QLatin1String("search")) {
                    // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
                    // for timeline and search should be a Dolphin-specific setting.
                    bookmark.setMetaDataItem("OnlyInApp", KGlobal::mainComponent().componentName());
                }

                PlacesItem* item = new PlacesItem(bookmark);
                item->setSystemItem(true);
                item->setGroup(data.group);
                appendItem(item);
            }
        }
    }

    // Create items for devices that have not stored as bookmark yet
    foreach (const QString& udi, devices) {
        const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
        devicesItems.append(new PlacesItem(bookmark));
    }

    addItems(devicesItems);

#ifdef PLACESITEMMODEL_DEBUG
    kDebug() << "Loaded bookmarks";
    showModelState();
#endif
}

void PlacesItemModel::addItems(const QList<PlacesItem*>& items)
{
    foreach (PlacesItem* item, items) {
        if (!m_hiddenItemsShown && item->isHidden()) {
            m_hiddenItems.append(item);
        } else {
            appendItem(item);
        }
    }
}

void PlacesItemModel::createSystemBookmarks()
{
    Q_ASSERT(m_systemBookmarks.isEmpty());
    Q_ASSERT(m_systemBookmarksIndexes.isEmpty());

    const QString placesGroup = placesGroupName();
    const QString recentlyAccessedGroup = recentlyAccessedGroupName();
    const QString searchForGroup = searchForGroupName();
    const QString timeLineIcon = "package_utility_time"; // TODO: Ask the Oxygen team to create
                                                         // a custom icon for the timeline-protocol

    m_systemBookmarks.append(SystemBookmarkData(KUrl(KUser().homeDir()),
                                                "user-home",
                                                i18nc("@item", "Home"),
                                                placesGroup));
    m_systemBookmarks.append(SystemBookmarkData(KUrl("remote:/"),
                                                "network-workgroup",
                                                i18nc("@item", "Network"),
                                                placesGroup));
    m_systemBookmarks.append(SystemBookmarkData(KUrl("/"),
                                                "folder-red",
                                                i18nc("@item", "Root"),
                                                placesGroup));
    m_systemBookmarks.append(SystemBookmarkData(KUrl("trash:/"),
                                                "user-trash",
                                                i18nc("@item", "Trash"),
                                                placesGroup));

    if (m_nepomukRunning) {
        m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/today"),
                                                    timeLineIcon,
                                                    i18nc("@item Recently Accessed", "Today"),
                                                    recentlyAccessedGroup));
        m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/yesterday"),
                                                    timeLineIcon,
                                                    i18nc("@item Recently Accessed", "Yesterday"),
                                                    recentlyAccessedGroup));
        m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/thismonth"),
                                                    timeLineIcon,
                                                    i18nc("@item Recently Accessed", "This Month"),
                                                    recentlyAccessedGroup));
        m_systemBookmarks.append(SystemBookmarkData(KUrl("timeline:/lastmonth"),
                                                    timeLineIcon,
                                                    i18nc("@item Recently Accessed", "Last Month"),
                                                    recentlyAccessedGroup));
        m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/documents"),
                                                    "folder-txt",
                                                    i18nc("@item Commonly Accessed", "Documents"),
                                                    searchForGroup));
        m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/images"),
                                                    "folder-image",
                                                    i18nc("@item Commonly Accessed", "Images"),
                                                    searchForGroup));
        m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/audio"),
                                                    "folder-sound",
                                                    i18nc("@item Commonly Accessed", "Audio Files"),
                                                    searchForGroup));
        m_systemBookmarks.append(SystemBookmarkData(KUrl("search:/videos"),
                                                    "folder-video",
                                                    i18nc("@item Commonly Accessed", "Videos"),
                                                    searchForGroup));
    }

    for (int i = 0; i < m_systemBookmarks.count(); ++i) {
        m_systemBookmarksIndexes.insert(m_systemBookmarks[i].url, i);
    }
}

void PlacesItemModel::initializeAvailableDevices()
{
    m_predicate = Solid::Predicate::fromString(
        "[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
        " OR "
        "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
        " OR "
        "OpticalDisc.availableContent & 'Audio' ]"
        " OR "
        "StorageAccess.ignored == false ]");
    Q_ASSERT(m_predicate.isValid());

    Solid::DeviceNotifier* notifier = Solid::DeviceNotifier::instance();
    connect(notifier, SIGNAL(deviceAdded(QString)),   this, SLOT(slotDeviceAdded(QString)));
    connect(notifier, SIGNAL(deviceRemoved(QString)), this, SLOT(slotDeviceRemoved(QString)));

    const QList<Solid::Device>& deviceList = Solid::Device::listFromQuery(m_predicate);
    foreach(const Solid::Device& device, deviceList) {
        m_availableDevices << device.udi();
    }
}

int PlacesItemModel::hiddenIndex(int index) const
{
    int hiddenIndex = 0;
    int visibleItemIndex = 0;
    while (hiddenIndex < m_hiddenItems.count()) {
        if (!m_hiddenItems[hiddenIndex]) {
            if (visibleItemIndex == index) {
                break;
            }
            ++visibleItemIndex;
        }
        ++hiddenIndex;
    }

    return hiddenIndex >= m_hiddenItems.count() ? -1 : hiddenIndex;
}

QString PlacesItemModel::placesGroupName()
{
    return i18nc("@item", "Places");
}

QString PlacesItemModel::recentlyAccessedGroupName()
{
    return i18nc("@item", "Recently Accessed");
}

QString PlacesItemModel::searchForGroupName()
{
    return i18nc("@item", "Search For");
}

#ifdef PLACESITEMMODEL_DEBUG
void PlacesItemModel::showModelState()
{
    kDebug() << "hidden-index   model-index   text";
    int j = 0;
    for (int i = 0; i < m_hiddenItems.count(); ++i) {
        if (m_hiddenItems[i]) {
            kDebug() <<  i << "(Hidden)    " << "             " << m_hiddenItems[i]->dataValue("text").toString();
        } else {
            if (item(j)) {
                kDebug() <<  i << "            " << j << "           " << item(j)->dataValue("text").toString();
            } else {
                kDebug() <<  i << "            " << j << "           " << "(not available yet)";
            }
            ++j;
        }
    }
}
#endif

#include "placesitemmodel.moc"