diff --git a/autotests/kfileplacesmodeltest.cpp b/autotests/kfileplacesmodeltest.cpp index 50a85cdc..6479264f 100644 --- a/autotests/kfileplacesmodeltest.cpp +++ b/autotests/kfileplacesmodeltest.cpp @@ -1,1304 +1,1304 @@ /* This file is part of the KDE project Copyright (C) 2007 Kevin Ottens This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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 #include #include #include #include #include #include #include #include #include #include #include #include Q_DECLARE_METATYPE(KFilePlacesModel::GroupType) #ifdef Q_OS_WIN //c:\ as root for windows #define KDE_ROOT_PATH "C:\\" #else #define KDE_ROOT_PATH "/" #endif // Avoid QHash randomization so that the order of the devices is stable static void seedInit() { qputenv("QT_HASH_SEED", "0"); // This env var has no effect because this comes too late. qCpuFeatures() was already called by // a Q_CONSTRUCTOR_FUNCTION inside QtGui (see image/qimage_conversions.cpp). Argh. QTBUG-47566. qputenv("QT_NO_CPU_FEATURE", "sse4.2"); } Q_CONSTRUCTOR_FUNCTION(seedInit) class KFilePlacesModelTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void testInitialState(); void testInitialList(); void testReparse(); void testInternalBookmarksHaveIds(); void testHiding(); void testMove(); void testPlacesLifecycle(); void testDevicePlugging(); void testDragAndDrop(); void testDeviceSetupTeardown(); void testEnableBaloo(); void testRemoteUrls_data(); void testRemoteUrls(); void testRefresh(); void testConvertedUrl_data(); void testConvertedUrl(); void testBookmarkObject(); void testDataChangedSignal(); void testIconRole_data(); void testIconRole(); void testMoveFunction(); void testPlaceGroupHidden(); void testPlaceGroupHiddenVsPlaceChildShown(); void testPlaceGroupHiddenAndShownWithHiddenChild(); void testPlaceGroupHiddenGroupIndexesIntegrity(); void testPlaceGroupHiddenSignal(); void testPlaceGroupHiddenRole(); void testFilterWithAlternativeApplicationName(); void testSupportedSchemes(); private: QStringList placesUrls(KFilePlacesModel *model = nullptr) const; QDBusInterface *fakeManager(); QDBusInterface *fakeDevice(const QString &udi); KFilePlacesModel *m_places; KFilePlacesModel *m_places2; // To check that they always stay in sync // actually supposed to work across processes, // but much harder to test QMap m_interfacesMap; QTemporaryDir m_tmpHome; }; static QString bookmarksFile() { return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/user-places.xbel"); } void KFilePlacesModelTest::initTestCase() { QVERIFY(m_tmpHome.isValid()); qputenv("HOME", m_tmpHome.path().toUtf8()); // use a empty home dir qputenv("KDE_FORK_SLAVES", "yes"); // to avoid a runtime dependency on klauncher QStandardPaths::setTestModeEnabled(true); // Ensure we'll have a clean bookmark file to start QFile::remove(bookmarksFile()); // disable baloo by default KConfig config(QStringLiteral("baloofilerc")); KConfigGroup basicSettings = config.group("Basic Settings"); basicSettings.writeEntry("Indexing-Enabled", false); config.sync(); qRegisterMetaType(); qRegisterMetaType(); const QString fakeHw = QFINDTESTDATA("fakecomputer.xml"); QVERIFY(!fakeHw.isEmpty()); qputenv("SOLID_FAKEHW", QFile::encodeName(fakeHw)); m_places = new KFilePlacesModel(); m_places2 = new KFilePlacesModel(); } void KFilePlacesModelTest::cleanupTestCase() { delete m_places; delete m_places2; qDeleteAll(m_interfacesMap); QFile::remove(bookmarksFile()); } QStringList KFilePlacesModelTest::placesUrls(KFilePlacesModel *model) const { KFilePlacesModel *currentModel = model; if (!currentModel) { currentModel = m_places; } QStringList urls; for (int row = 0; row < currentModel->rowCount(); ++row) { QModelIndex index = currentModel->index(row, 0); urls << currentModel->url(index).toDisplayString(QUrl::PreferLocalFile); } return urls; } #define CHECK_PLACES_URLS(urls) \ if (placesUrls() != urls) { \ qDebug() << "Expected:" << urls; \ qDebug() << "Got:" << placesUrls(); \ QCOMPARE(placesUrls(), urls); \ } \ for (int row = 0; row < urls.size(); ++row) { \ QModelIndex index = m_places->index(row, 0); \ \ QCOMPARE(m_places->url(index).toString(), QUrl::fromUserInput(urls[row]).toString()); \ QCOMPARE(m_places->data(index, KFilePlacesModel::UrlRole).toUrl(), \ QUrl(m_places->url(index))); \ \ index = m_places2->index(row, 0); \ \ QCOMPARE(m_places2->url(index).toString(), QUrl::fromUserInput(urls[row]).toString()); \ QCOMPARE(m_places2->data(index, KFilePlacesModel::UrlRole).toUrl(), \ QUrl(m_places2->url(index))); \ } \ \ QCOMPARE(urls.size(), m_places->rowCount()); \ QCOMPARE(urls.size(), m_places2->rowCount()); QDBusInterface *KFilePlacesModelTest::fakeManager() { return fakeDevice(QStringLiteral("/org/kde/solid/fakehw")); } QDBusInterface *KFilePlacesModelTest::fakeDevice(const QString &udi) { QDBusInterface *interface = m_interfacesMap[udi]; if (interface) { return interface; } QDBusInterface *iface = new QDBusInterface(QDBusConnection::sessionBus().baseService(), udi); m_interfacesMap[udi] = iface; return iface; } void KFilePlacesModelTest::testInitialState() { QCOMPARE(m_places->rowCount(), 4); // when the xbel file is empty, KFilePlacesModel fills it with 4 default items QCoreApplication::processEvents(); // Devices have a delayed loading QCOMPARE(m_places->rowCount(), 9); } static const QStringList initialListOfPlaces() { return QStringList() << QDir::homePath() << QStringLiteral(KDE_ROOT_PATH) << QStringLiteral("trash:/"); } static const QStringList initialListOfShared() { return QStringList() << QStringLiteral("remote:/") << QStringLiteral("/media/nfs"); } static const QStringList initialListOfDevices() { return QStringList() << QStringLiteral("/foreign"); } static const QStringList initialListOfRemovableDevices() { return QStringList() << QStringLiteral("/media/floppy0") << QStringLiteral("/media/XO-Y4") << QStringLiteral("/media/cdrom"); } static const QStringList initialListOfUrls() { return QStringList() << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); } void KFilePlacesModelTest::testInitialList() { const QStringList urls = initialListOfUrls(); CHECK_PLACES_URLS(urls); } void KFilePlacesModelTest::testReparse() { QStringList urls; // add item m_places->addPlace(QStringLiteral("foo"), QUrl::fromLocalFile(QStringLiteral("/foo")), QString(), QString()); urls = initialListOfUrls(); // it will be added at the end of places section urls.insert(3, QStringLiteral("/foo")); CHECK_PLACES_URLS(urls); // reparse the bookmark file KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(bookmarksFile(), QStringLiteral("kfilePlaces")); bookmarkManager->notifyCompleteChange(QString()); // check if they are the same CHECK_PLACES_URLS(urls); // try to remove item m_places->removePlace(m_places->index(3, 0)); urls = initialListOfUrls(); CHECK_PLACES_URLS(urls); } void KFilePlacesModelTest::testInternalBookmarksHaveIds() { KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(bookmarksFile(), QStringLiteral("kfilePlaces")); KBookmarkGroup root = bookmarkManager->root(); // Verify every entry has an id or an udi KBookmark bookmark = root.first(); while (!bookmark.isNull()) { QVERIFY(!bookmark.metaDataItem(QStringLiteral("ID")).isEmpty() || !bookmark.metaDataItem(QStringLiteral("UDI")).isEmpty()); // It's mutualy exclusive though QVERIFY(bookmark.metaDataItem(QStringLiteral("ID")).isEmpty() || bookmark.metaDataItem(QStringLiteral("UDI")).isEmpty()); bookmark = root.next(bookmark); } // Verify that adding a bookmark behind its back the model gives it an id // (in real life it requires the user to modify the file by hand, // unlikely but better safe than sorry). // It induces a small race condition which means several ids will be // successively set on the same bookmark but no big deal since it won't // break the system KBookmark foo = root.addBookmark(QStringLiteral("Foo"), QUrl(QStringLiteral("file:/foo")), QStringLiteral("red-folder")); QCOMPARE(foo.text(), QStringLiteral("Foo")); QVERIFY(foo.metaDataItem(QStringLiteral("ID")).isEmpty()); bookmarkManager->emitChanged(root); QCOMPARE(foo.text(), QStringLiteral("Foo")); QVERIFY(!foo.metaDataItem(QStringLiteral("ID")).isEmpty()); // Verify that all the ids are different bookmark = root.first(); QSet ids; while (!bookmark.isNull()) { QString id; if (!bookmark.metaDataItem(QStringLiteral("UDI")).isEmpty()) { id = bookmark.metaDataItem(QStringLiteral("UDI")); } else { id = bookmark.metaDataItem(QStringLiteral("ID")); } QVERIFY2(!ids.contains(id), "Duplicated ID found!"); ids << id; bookmark = root.next(bookmark); } // Cleanup foo root.deleteBookmark(foo); bookmarkManager->emitChanged(root); } void KFilePlacesModelTest::testHiding() { // Verify that nothing is hidden for (int row = 0; row < m_places->rowCount(); ++row) { QModelIndex index = m_places->index(row, 0); QVERIFY(!m_places->isHidden(index)); } QModelIndex a = m_places->index(2, 0); QModelIndex b = m_places->index(6, 0); QList args; QSignalSpy spy(m_places, SIGNAL(dataChanged(QModelIndex,QModelIndex))); // Verify that hidden is taken into account and is not global m_places->setPlaceHidden(a, true); QVERIFY(m_places->isHidden(a)); QVERIFY(m_places->data(a, KFilePlacesModel::HiddenRole).toBool()); QVERIFY(!m_places->isHidden(b)); QVERIFY(!m_places->data(b, KFilePlacesModel::HiddenRole).toBool()); QCOMPARE(spy.count(), 1); args = spy.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), a); QCOMPARE(args.at(1).toModelIndex(), a); m_places->setPlaceHidden(b, true); QVERIFY(m_places->isHidden(a)); QVERIFY(m_places->data(a, KFilePlacesModel::HiddenRole).toBool()); QVERIFY(m_places->isHidden(b)); QVERIFY(m_places->data(b, KFilePlacesModel::HiddenRole).toBool()); QCOMPARE(spy.count(), 1); args = spy.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), b); QCOMPARE(args.at(1).toModelIndex(), b); m_places->setPlaceHidden(a, false); m_places->setPlaceHidden(b, false); QVERIFY(!m_places->isHidden(a)); QVERIFY(!m_places->data(a, KFilePlacesModel::HiddenRole).toBool()); QVERIFY(!m_places->isHidden(b)); QVERIFY(!m_places->data(b, KFilePlacesModel::HiddenRole).toBool()); QCOMPARE(spy.count(), 2); args = spy.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), a); QCOMPARE(args.at(1).toModelIndex(), a); args = spy.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), b); QCOMPARE(args.at(1).toModelIndex(), b); } void KFilePlacesModelTest::testMove() { QList args; QSignalSpy spy_inserted(m_places, SIGNAL(rowsInserted(QModelIndex,int,int))); QSignalSpy spy_removed(m_places, SIGNAL(rowsRemoved(QModelIndex,int,int))); KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(bookmarksFile(), QStringLiteral("kfilePlaces")); KBookmarkGroup root = bookmarkManager->root(); KBookmark system_root = m_places->bookmarkForIndex(m_places->index(1, 0)); KBookmark before_system_root = m_places->bookmarkForIndex(m_places->index(0, 0)); // Trying move the root at the end of the list, should move it to the end of places section instead // to keep it grouped KBookmark last = root.first(); while (!root.next(last).isNull()) { last = root.next(last); } root.moveBookmark(system_root, last); bookmarkManager->emitChanged(root); QStringList urls; urls << QDir::homePath() << QStringLiteral("trash:/") << QStringLiteral(KDE_ROOT_PATH) << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 2); QCOMPARE(args.at(2).toInt(), 2); QCOMPARE(spy_removed.count(), 1); args = spy_removed.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 1); QCOMPARE(args.at(2).toInt(), 1); // Move the root at the beginning of the list root.moveBookmark(system_root, KBookmark()); bookmarkManager->emitChanged(root); urls.clear(); urls << QStringLiteral(KDE_ROOT_PATH) << QDir::homePath() << QStringLiteral("trash:/") << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 0); QCOMPARE(args.at(2).toInt(), 0); QCOMPARE(spy_removed.count(), 1); args = spy_removed.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 3); QCOMPARE(args.at(2).toInt(), 3); // Move the root in the list (at its original place) root.moveBookmark(system_root, before_system_root); bookmarkManager->emitChanged(root); urls.clear(); urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 1); QCOMPARE(args.at(2).toInt(), 1); QCOMPARE(spy_removed.count(), 1); args = spy_removed.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 0); QCOMPARE(args.at(2).toInt(), 0); } void KFilePlacesModelTest::testDragAndDrop() { QList args; QSignalSpy spy_moved(m_places, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int))); // Monitor rowsInserted() and rowsRemoved() to ensure they are never emitted: // Moving with drag and drop is expected to emit rowsMoved() QSignalSpy spy_inserted(m_places, SIGNAL(rowsInserted(QModelIndex,int,int))); QSignalSpy spy_removed(m_places, SIGNAL(rowsRemoved(QModelIndex,int,int))); // Move the KDE_ROOT_PATH at the end of the places list QModelIndexList indexes; indexes << m_places->index(1, 0); QMimeData *mimeData = m_places->mimeData(indexes); QVERIFY(m_places->dropMimeData(mimeData, Qt::MoveAction, 3, 0, QModelIndex())); QStringList urls; urls << QDir::homePath() << QStringLiteral("trash:/") << QStringLiteral(KDE_ROOT_PATH) << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 0); QCOMPARE(spy_removed.count(), 0); QCOMPARE(spy_moved.count(), 1); args = spy_moved.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 1); QCOMPARE(args.at(2).toInt(), 1); QCOMPARE(args.at(3).toModelIndex(), QModelIndex()); QCOMPARE(args.at(4).toInt(), 3); // Move the KDE_ROOT_PATH at the beginning of the list indexes.clear(); indexes << m_places->index(2, 0); mimeData = m_places->mimeData(indexes); QVERIFY(m_places->dropMimeData(mimeData, Qt::MoveAction, 0, 0, QModelIndex())); urls.clear(); urls << QStringLiteral(KDE_ROOT_PATH) << QDir::homePath() << QStringLiteral("trash:/") << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 0); QCOMPARE(spy_removed.count(), 0); QCOMPARE(spy_moved.count(), 1); args = spy_moved.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 2); QCOMPARE(args.at(2).toInt(), 2); QCOMPARE(args.at(3).toModelIndex(), QModelIndex()); QCOMPARE(args.at(4).toInt(), 0); // Move the KDE_ROOT_PATH in the list (at its original place) indexes.clear(); indexes << m_places->index(0, 0); mimeData = m_places->mimeData(indexes); QVERIFY(m_places->dropMimeData(mimeData, Qt::MoveAction, 2, 0, QModelIndex())); urls.clear(); urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 0); QCOMPARE(spy_removed.count(), 0); QCOMPARE(spy_moved.count(), 1); args = spy_moved.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 0); QCOMPARE(args.at(2).toInt(), 0); QCOMPARE(args.at(3).toModelIndex(), QModelIndex()); QCOMPARE(args.at(4).toInt(), 2); // Dropping on an item is not allowed indexes.clear(); indexes << m_places->index(4, 0); mimeData = m_places->mimeData(indexes); QVERIFY(!m_places->dropMimeData(mimeData, Qt::MoveAction, -1, 0, m_places->index(2, 0))); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 0); QCOMPARE(spy_removed.count(), 0); QCOMPARE(spy_moved.count(), 0); } void KFilePlacesModelTest::testPlacesLifecycle() { QList args; QSignalSpy spy_inserted(m_places, SIGNAL(rowsInserted(QModelIndex,int,int))); QSignalSpy spy_removed(m_places, SIGNAL(rowsRemoved(QModelIndex,int,int))); QSignalSpy spy_changed(m_places, SIGNAL(dataChanged(QModelIndex,QModelIndex))); m_places->addPlace(QStringLiteral("Foo"), QUrl::fromLocalFile(QStringLiteral("/home/foo"))); QStringList urls; urls << initialListOfPlaces() << QStringLiteral("/home/foo") << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 3); QCOMPARE(args.at(2).toInt(), 3); QCOMPARE(spy_removed.count(), 0); KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(bookmarksFile(), QStringLiteral("kfilePlaces")); KBookmarkGroup root = bookmarkManager->root(); KBookmark before_trash = m_places->bookmarkForIndex(m_places->index(1, 0)); KBookmark foo = m_places->bookmarkForIndex(m_places->index(3, 0)); root.moveBookmark(foo, before_trash); bookmarkManager->emitChanged(root); urls.clear(); urls << QDir::homePath() << QStringLiteral(KDE_ROOT_PATH) << QStringLiteral("/home/foo") << QStringLiteral("trash:/") << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 3); QCOMPARE(args.at(2).toInt(), 3); QCOMPARE(spy_removed.count(), 1); args = spy_removed.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 2); QCOMPARE(args.at(2).toInt(), 2); m_places->editPlace(m_places->index(2, 0), QStringLiteral("Foo"), QUrl::fromLocalFile(QStringLiteral("/mnt/foo"))); urls.clear(); urls << QDir::homePath() << QStringLiteral(KDE_ROOT_PATH) << QStringLiteral("/mnt/foo") << QStringLiteral("trash:/") << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 0); QCOMPARE(spy_removed.count(), 0); QCOMPARE(spy_changed.count(), 1); args = spy_changed.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), m_places->index(2, 0)); QCOMPARE(args.at(1).toModelIndex(), m_places->index(2, 0)); foo = m_places->bookmarkForIndex(m_places->index(2, 0)); foo.setFullText(QStringLiteral("Bar")); bookmarkManager->notifyCompleteChange(QString()); urls.clear(); urls << QDir::homePath() << QStringLiteral(KDE_ROOT_PATH) << QStringLiteral("/mnt/foo") << QStringLiteral("trash:/") << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 0); QCOMPARE(spy_removed.count(), 0); QCOMPARE(spy_changed.count(), 10); args = spy_changed[2]; QCOMPARE(args.at(0).toModelIndex(), m_places->index(2, 0)); QCOMPARE(args.at(1).toModelIndex(), m_places->index(2, 0)); spy_changed.clear(); m_places->removePlace(m_places->index(2, 0)); urls.clear(); urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 0); QCOMPARE(spy_removed.count(), 1); args = spy_removed.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 2); QCOMPARE(args.at(2).toInt(), 2); m_places->addPlace(QStringLiteral("Foo"), QUrl::fromLocalFile(QStringLiteral("/home/foo")), QString(), QString(), m_places->index(0, 0)); urls.clear(); urls << QDir::homePath() << QStringLiteral("/home/foo") << QStringLiteral(KDE_ROOT_PATH) << QStringLiteral("trash:/") << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 1); QCOMPARE(args.at(2).toInt(), 1); QCOMPARE(spy_removed.count(), 0); m_places->removePlace(m_places->index(1, 0)); } void KFilePlacesModelTest::testDevicePlugging() { QList args; QSignalSpy spy_inserted(m_places, SIGNAL(rowsInserted(QModelIndex,int,int))); QSignalSpy spy_removed(m_places, SIGNAL(rowsRemoved(QModelIndex,int,int))); fakeManager()->call(QStringLiteral("unplug"), "/org/kde/solid/fakehw/volume_part1_size_993284096"); QStringList urls; urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << QStringLiteral("/media/floppy0") << QStringLiteral("/media/cdrom"); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 0); QCOMPARE(spy_removed.count(), 1); args = spy_removed.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 7); QCOMPARE(args.at(2).toInt(), 7); fakeManager()->call(QStringLiteral("plug"), "/org/kde/solid/fakehw/volume_part1_size_993284096"); urls.clear(); urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 7); QCOMPARE(args.at(2).toInt(), 7); QCOMPARE(spy_removed.count(), 0); // Move the device in the list, and check that it memorizes the position across plug/unplug KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(bookmarksFile(), QStringLiteral("kfilePlaces")); KBookmarkGroup root = bookmarkManager->root(); KBookmark before_floppy; KBookmark device = root.first(); // The device we'll move is the 7th bookmark for (int i = 0; i < 6; i++) { if (i == 3) { // store item before to be able to move it back to original position device = before_floppy = root.next(device); } else { device = root.next(device); } } root.moveBookmark(device, before_floppy); bookmarkManager->emitChanged(root); urls.clear(); urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << QStringLiteral("/media/XO-Y4") << QStringLiteral("/media/floppy0") << QStringLiteral("/media/cdrom"); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 7); QCOMPARE(args.at(2).toInt(), 7); QCOMPARE(spy_removed.count(), 1); args = spy_removed.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 6); QCOMPARE(args.at(2).toInt(), 6); fakeManager()->call(QStringLiteral("unplug"), "/org/kde/solid/fakehw/volume_part1_size_993284096"); urls.clear(); urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << QStringLiteral("/media/floppy0") << QStringLiteral("/media/cdrom"); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 0); QCOMPARE(spy_removed.count(), 1); args = spy_removed.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 6); QCOMPARE(args.at(2).toInt(), 6); fakeManager()->call(QStringLiteral("plug"), "/org/kde/solid/fakehw/volume_part1_size_993284096"); urls.clear(); urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << QStringLiteral("/media/XO-Y4") << QStringLiteral("/media/floppy0") << QStringLiteral("/media/cdrom"); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 6); QCOMPARE(args.at(2).toInt(), 6); QCOMPARE(spy_removed.count(), 0); KBookmark seventh = root.first(); for (int i = 0; i < 6; i++) { seventh = root.next(seventh); } root.moveBookmark(device, seventh); bookmarkManager->emitChanged(root); urls.clear(); urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QCOMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 7); QCOMPARE(args.at(2).toInt(), 7); QCOMPARE(spy_removed.count(), 1); args = spy_removed.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), 6); QCOMPARE(args.at(2).toInt(), 6); } void KFilePlacesModelTest::testDeviceSetupTeardown() { QList args; QSignalSpy spy_changed(m_places, SIGNAL(dataChanged(QModelIndex,QModelIndex))); fakeDevice(QStringLiteral("/org/kde/solid/fakehw/volume_part1_size_993284096/StorageAccess"))->call(QStringLiteral("teardown")); QCOMPARE(spy_changed.count(), 1); args = spy_changed.takeFirst(); QCOMPARE(args.at(0).toModelIndex().row(), 7); QCOMPARE(args.at(1).toModelIndex().row(), 7); fakeDevice(QStringLiteral("/org/kde/solid/fakehw/volume_part1_size_993284096/StorageAccess"))->call(QStringLiteral("setup")); QCOMPARE(spy_changed.count(), 1); args = spy_changed.takeFirst(); QCOMPARE(args.at(0).toModelIndex().row(), 7); QCOMPARE(args.at(1).toModelIndex().row(), 7); } void KFilePlacesModelTest::testEnableBaloo() { KConfig config(QStringLiteral("baloofilerc")); KConfigGroup basicSettings = config.group("Basic Settings"); basicSettings.writeEntry("Indexing-Enabled", true); config.sync(); KFilePlacesModel places_with_baloo; QStringList urls; for (int row = 0; row < places_with_baloo.rowCount(); ++row) { QModelIndex index = places_with_baloo.index(row, 0); urls << places_with_baloo.url(index).toDisplayString(QUrl::PreferLocalFile); } QVERIFY(urls.contains("timeline:/today")); QVERIFY(urls.contains("timeline:/yesterday")); QVERIFY(urls.contains("search:/documents")); QVERIFY(urls.contains("search:/images")); QVERIFY(urls.contains("search:/audio")); QVERIFY(urls.contains("search:/videos")); } void KFilePlacesModelTest::testRemoteUrls_data() { QTest::addColumn("url"); QTest::addColumn("expectedRow"); QTest::addColumn("expectedGroup"); QTest::newRow("Ftp") << QUrl(QStringLiteral("ftp://192.168.1.1/ftp")) << 5 << QStringLiteral("Remote"); QTest::newRow("Samba") << QUrl(QStringLiteral("smb://192.168.1.1/share")) << 5 << QStringLiteral("Remote"); QTest::newRow("Sftp") << QUrl(QStringLiteral("sftp://192.168.1.1/share")) << 5 << QStringLiteral("Remote"); QTest::newRow("Fish") << QUrl(QStringLiteral("fish://192.168.1.1/share")) << 5 << QStringLiteral("Remote"); QTest::newRow("Webdav") << QUrl(QStringLiteral("webdav://192.168.1.1/share")) << 5 << QStringLiteral("Remote"); } void KFilePlacesModelTest::testRemoteUrls() { QFETCH(QUrl, url); QFETCH(int, expectedRow); QFETCH(QString, expectedGroup); QList args; QSignalSpy spy_inserted(m_places, SIGNAL(rowsInserted(QModelIndex,int,int))); // insert a new network url m_places->addPlace(QStringLiteral("My Shared"), url, QString(), QString(), QModelIndex()); // check if url list is correct after insertion QStringList urls; urls << QDir::homePath() << QStringLiteral(KDE_ROOT_PATH) << QStringLiteral("trash:/") // places << QStringLiteral("remote:/") << QStringLiteral("/media/nfs") << url.toString() << QStringLiteral("/foreign") << QStringLiteral("/media/floppy0") << QStringLiteral("/media/XO-Y4") << QStringLiteral("/media/cdrom"); CHECK_PLACES_URLS(urls); // check if the new url was inserted in the right position (end of "Remote" section) QTRY_COMPARE(spy_inserted.count(), 1); args = spy_inserted.takeFirst(); QCOMPARE(args.at(0).toModelIndex(), QModelIndex()); QCOMPARE(args.at(1).toInt(), expectedRow); QCOMPARE(args.at(2).toInt(), expectedRow); // check if the new url has the right group "Remote" const QModelIndex index = m_places->index(expectedRow, 0); QCOMPARE(index.data(KFilePlacesModel::GroupRole).toString(), expectedGroup); m_places->removePlace(index); } void KFilePlacesModelTest::testRefresh() { KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(bookmarksFile(), QStringLiteral("kfilePlaces")); KBookmarkGroup root = bookmarkManager->root(); KBookmark homePlace = root.first(); const QModelIndex homePlaceIndex = m_places->index(0, 0); QCOMPARE(m_places->text(homePlaceIndex), homePlace.fullText()); // modify bookmark homePlace.setFullText("Test change the text"); QVERIFY(m_places->text(homePlaceIndex) != homePlace.fullText()); // reload bookmark data m_places->refresh(); QCOMPARE(m_places->text(homePlaceIndex), homePlace.fullText()); } void KFilePlacesModelTest::testConvertedUrl_data() { QTest::addColumn("url"); QTest::addColumn("expectedUrl"); // places QTest::newRow("Places - Home") << QUrl::fromLocalFile(QDir::homePath()) << QUrl::fromLocalFile(QDir::homePath()); // baloo -search QTest::newRow("Baloo - Documents") << QUrl("search:/documents") << QUrl("baloosearch:/documents"); QTest::newRow("Baloo - Unknown Type") << QUrl("search:/unknown") << QUrl("search:/unknown"); // baloo - timeline const QDate lastMonthDate = QDate::currentDate().addMonths(-1); QTest::newRow("Baloo - Last Month") << QUrl("timeline:/lastmonth") << QUrl(QString("timeline:/%1-%2").arg(lastMonthDate.year()).arg(lastMonthDate.month(), 2, 10, QLatin1Char('0'))); // devices QTest::newRow("Devices - Floppy") << QUrl("file:///media/floppy0") << QUrl("file:///media/floppy0"); } void KFilePlacesModelTest::testConvertedUrl() { QFETCH(QUrl, url); QFETCH(QUrl, expectedUrl); const QUrl convertedUrl = KFilePlacesModel::convertedUrl(url); QCOMPARE(convertedUrl.scheme(), expectedUrl.scheme()); QCOMPARE(convertedUrl.path(), expectedUrl.path()); QCOMPARE(convertedUrl, expectedUrl); } void KFilePlacesModelTest::testBookmarkObject() { //make sure that all items return a valid bookmark for (int row = 0; row < m_places->rowCount(); row++) { const QModelIndex index = m_places->index(row, 0); const KBookmark bookmark = m_places->bookmarkForIndex(index); QVERIFY(!bookmark.isNull()); } } void KFilePlacesModelTest::testDataChangedSignal() { QSignalSpy dataChangedSpy(m_places, &KFilePlacesModel::dataChanged); const QModelIndex index = m_places->index(1, 0); const KBookmark bookmark = m_places->bookmarkForIndex(index); // call function with the same data m_places->editPlace(index, bookmark.fullText(), bookmark.url(), bookmark.icon(), bookmark.metaDataItem(QStringLiteral("OnlyInApp"))); QCOMPARE(dataChangedSpy.count(), 0); // call function with different data const QString originalText = bookmark.fullText(); m_places->editPlace(index, QStringLiteral("My text"), bookmark.url(), bookmark.icon(), bookmark.metaDataItem(QStringLiteral("OnlyInApp"))); QCOMPARE(dataChangedSpy.count(), 1); QList args = dataChangedSpy.takeFirst(); QCOMPARE(args.at(0).toModelIndex().row(), 1); QCOMPARE(args.at(0).toModelIndex().column(), 0); QCOMPARE(args.at(1).toModelIndex().row(), 1); QCOMPARE(args.at(1).toModelIndex().column(), 0); QCOMPARE(m_places->text(index), QStringLiteral("My text")); // restore original value dataChangedSpy.clear(); m_places->editPlace(index, originalText, bookmark.url(), bookmark.icon(), bookmark.metaDataItem(QStringLiteral("OnlyInApp"))); QCOMPARE(dataChangedSpy.count(), 1); } void KFilePlacesModelTest::testIconRole_data() { QTest::addColumn("index"); QTest::addColumn("expectedIconName"); // places QTest::newRow("Places - Home") << m_places->index(0, 0) << QStringLiteral("user-home"); QTest::newRow("Places - Root") << m_places->index(1, 0) << QStringLiteral("folder-red"); QTest::newRow("Places - Trash") << m_places->index(2, 0) << QStringLiteral("user-trash"); QTest::newRow("Remote - Network") << m_places->index(3, 0) - << QStringLiteral("network-workgroup"); + << QStringLiteral("folder-network"); QTest::newRow("Devices - Nfs") << m_places->index(4, 0) << QStringLiteral("hwinfo"); QTest::newRow("Devices - foreign") << m_places->index(5, 0) << QStringLiteral("blockdevice"); QTest::newRow("Devices - Floppy") << m_places->index(6, 0) << QStringLiteral("blockdevice"); QTest::newRow("Devices - cdrom") << m_places->index(7, 0) << QStringLiteral("blockdevice"); } void KFilePlacesModelTest::testIconRole() { QFETCH(QModelIndex, index); QFETCH(QString, expectedIconName); QVERIFY(index.data(KFilePlacesModel::IconNameRole).toString().startsWith(expectedIconName)); } void KFilePlacesModelTest::testMoveFunction() { QList args; QStringList urls = initialListOfUrls(); QSignalSpy rowsMoved(m_places, &KFilePlacesModel::rowsMoved); // move item 0 to pos 2 QVERIFY(m_places->movePlace(0, 3)); urls.move(0, 2); QTRY_COMPARE(rowsMoved.count(), 1); args = rowsMoved.takeFirst(); QCOMPARE(args.at(1).toInt(), 0); // start QCOMPARE(args.at(2).toInt(), 0); // end QCOMPARE(args.at(4).toInt(), 3); // row (destination) QCOMPARE(placesUrls(), urls); rowsMoved.clear(); // move it back QVERIFY(m_places->movePlace(2, 0)); urls.move(2, 0); QTRY_COMPARE(rowsMoved.count(), 1); args = rowsMoved.takeFirst(); QCOMPARE(args.at(1).toInt(), 2); // start QCOMPARE(args.at(2).toInt(), 2); // end QCOMPARE(args.at(4).toInt(), 0); // row (destination) QCOMPARE(placesUrls(), urls); rowsMoved.clear(); // target position is greater than model rows // will move to the end of the first group QVERIFY(m_places->movePlace(0, 20)); urls.move(0, 2); QTRY_COMPARE(rowsMoved.count(), 1); args = rowsMoved.takeFirst(); QCOMPARE(args.at(1).toInt(), 0); // start QCOMPARE(args.at(2).toInt(), 0); // end QCOMPARE(args.at(4).toInt(), 3); // row (destination) QCOMPARE(placesUrls(), urls); rowsMoved.clear(); // move it back QVERIFY(m_places->movePlace(2, 0)); urls.move(2, 0); QTRY_COMPARE(rowsMoved.count(), 1); args = rowsMoved.takeFirst(); QCOMPARE(args.at(1).toInt(), 2); // start QCOMPARE(args.at(2).toInt(), 2); // end QCOMPARE(args.at(4).toInt(), 0); // row (destination) QCOMPARE(placesUrls(), urls); rowsMoved.clear(); QVERIFY(m_places->movePlace(8, 6)); urls.move(8, 6); QTRY_COMPARE(rowsMoved.count(), 1); args = rowsMoved.takeFirst(); QCOMPARE(args.at(1).toInt(), 8); // start QCOMPARE(args.at(2).toInt(), 8); // end QCOMPARE(args.at(4).toInt(), 6); // row (destination) QCOMPARE(placesUrls(), urls); rowsMoved.clear(); // move it back QVERIFY(m_places->movePlace(6, 9)); urls.move(6, 8); QTRY_COMPARE(rowsMoved.count(), 1); args = rowsMoved.takeFirst(); QCOMPARE(args.at(1).toInt(), 6); // start QCOMPARE(args.at(2).toInt(), 6); // end QCOMPARE(args.at(4).toInt(), 9); // row (destination) QCOMPARE(placesUrls(), urls); rowsMoved.clear(); //use a invalid start position QVERIFY(!m_places->movePlace(100, 20)); QCOMPARE(rowsMoved.count(), 0); //use same start and target position QVERIFY(!m_places->movePlace(1, 1)); QCOMPARE(rowsMoved.count(), 0); } void KFilePlacesModelTest::testPlaceGroupHidden() { // GIVEN QCOMPARE(m_places->hiddenCount(), 0); QStringList urls; urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QVector indexesHidden; // WHEN m_places->setGroupHidden(KFilePlacesModel::PlacesType, true); // THEN for (int row = 0; row < m_places->rowCount(); ++row) { QModelIndex index = m_places->index(row, 0); if (m_places->groupType(index) == KFilePlacesModel::PlacesType) { QVERIFY(m_places->isHidden(index)); indexesHidden << index; } } QCOMPARE(indexesHidden.count(), initialListOfPlaces().size()); QCOMPARE(m_places->hiddenCount(), indexesHidden.size()); // and GIVEN QVector indexesShown; // WHEN m_places->setGroupHidden(KFilePlacesModel::PlacesType, false); // THEN for (int row = 0; row < m_places->rowCount(); ++row) { QModelIndex index = m_places->index(row, 0); if (m_places->groupType(index) == KFilePlacesModel::PlacesType) { QVERIFY(!m_places->isHidden(index)); indexesShown << index; } } QCOMPARE(m_places->hiddenCount(), 0); QCOMPARE(indexesShown.count(), initialListOfPlaces().size()); } void KFilePlacesModelTest::testPlaceGroupHiddenVsPlaceChildShown() { // GIVEN for (int row = 0; row < m_places->rowCount(); ++row) { QModelIndex index = m_places->index(row, 0); QVERIFY(!m_places->isHidden(index)); } m_places->setGroupHidden(KFilePlacesModel::PlacesType, true); QModelIndex firstIndex = m_places->index(0,0); const int amountOfPlaces = initialListOfPlaces().size(); for (int row = 0; row < amountOfPlaces; ++row) { QModelIndex index = m_places->index(row, 0); QVERIFY(m_places->isHidden(index)); } // WHEN m_places->setPlaceHidden(firstIndex, false); // THEN QVERIFY(m_places->isHidden(firstIndex)); // a child cannot show against its parent state // leaving in a clean state m_places->setGroupHidden(KFilePlacesModel::PlacesType, false); } void KFilePlacesModelTest::testPlaceGroupHiddenAndShownWithHiddenChild() { // GIVEN QCOMPARE(m_places->hiddenCount(), 0); QStringList urls; urls << initialListOfPlaces() << initialListOfShared() << initialListOfDevices() << initialListOfRemovableDevices(); CHECK_PLACES_URLS(urls); QModelIndex firstIndexHidden = m_places->index(0,0); m_places->setPlaceHidden(firstIndexHidden, true); // first place index is hidden within an hidden parent m_places->setGroupHidden(KFilePlacesModel::PlacesType, true); QCOMPARE(m_places->hiddenCount(), initialListOfPlaces().size()); // WHEN m_places->setGroupHidden(KFilePlacesModel::PlacesType, false); // THEN QVector indexesShown; for (int row = 0; row < m_places->rowCount(); ++row) { QModelIndex index = m_places->index(row, 0); if (index == firstIndexHidden) { QVERIFY(m_places->isHidden(firstIndexHidden)); continue; } if (m_places->groupType(index) == KFilePlacesModel::PlacesType) { QVERIFY(!m_places->isHidden(index)); indexesShown << index; } } QCOMPARE(m_places->hiddenCount(), 1); QCOMPARE(indexesShown.count(), initialListOfPlaces().size() - 1 /*first child remains hidden*/); // leaving in a clean state m_places->setPlaceHidden(firstIndexHidden, false); } void KFilePlacesModelTest::testPlaceGroupHiddenGroupIndexesIntegrity() { // GIVEN m_places->setGroupHidden(KFilePlacesModel::PlacesType, true); QVERIFY(m_places->groupIndexes(KFilePlacesModel::UnknownType).isEmpty()); QVERIFY(m_places->isGroupHidden(KFilePlacesModel::PlacesType)); QCOMPARE(m_places->groupIndexes(KFilePlacesModel::PlacesType).count(), initialListOfPlaces().count()); QCOMPARE(m_places->groupIndexes(KFilePlacesModel::RecentlySavedType).count(), 0); QCOMPARE(m_places->groupIndexes(KFilePlacesModel::SearchForType).count(), 0); QCOMPARE(m_places->groupIndexes(KFilePlacesModel::DevicesType).count(), initialListOfDevices().count()); QCOMPARE(m_places->groupIndexes(KFilePlacesModel::RemovableDevicesType).count(), initialListOfRemovableDevices().count()); //WHEN m_places->setGroupHidden(KFilePlacesModel::PlacesType, false); // THEN // Make sure that hidden place group doesn't change model QVERIFY(!m_places->isGroupHidden(KFilePlacesModel::PlacesType)); QCOMPARE(m_places->groupIndexes(KFilePlacesModel::PlacesType).count(), initialListOfPlaces().count()); QCOMPARE(m_places->groupIndexes(KFilePlacesModel::RecentlySavedType).count(), 0); QCOMPARE(m_places->groupIndexes(KFilePlacesModel::SearchForType).count(), 0); QCOMPARE(m_places->groupIndexes(KFilePlacesModel::DevicesType).count(), initialListOfDevices().count()); QCOMPARE(m_places->groupIndexes(KFilePlacesModel::RemovableDevicesType).count(), initialListOfRemovableDevices().count()); } void KFilePlacesModelTest::testPlaceGroupHiddenSignal() { QSignalSpy groupHiddenSignal(m_places, &KFilePlacesModel::groupHiddenChanged); m_places->setGroupHidden(KFilePlacesModel::SearchForType, true); // hide SearchForType group QTRY_COMPARE(groupHiddenSignal.count(), 1); QList args = groupHiddenSignal.takeFirst(); QCOMPARE(args.at(0).toInt(), static_cast(KFilePlacesModel::SearchForType)); QCOMPARE(args.at(1).toBool(), true); groupHiddenSignal.clear(); // try hide SearchForType which is already hidden m_places->setGroupHidden(KFilePlacesModel::SearchForType, true); QCOMPARE(groupHiddenSignal.count(), 0); // show SearchForType group m_places->setGroupHidden(KFilePlacesModel::SearchForType, false); QTRY_COMPARE(groupHiddenSignal.count(), 1); args = groupHiddenSignal.takeFirst(); QCOMPARE(args.at(0).toInt(), static_cast(KFilePlacesModel::SearchForType)); QCOMPARE(args.at(1).toBool(), false); } void KFilePlacesModelTest::testPlaceGroupHiddenRole() { // on startup all groups are visible for (int r = 0, rMax = m_places->rowCount(); r < rMax; r++) { const QModelIndex index = m_places->index(r, 0); QCOMPARE(index.data(KFilePlacesModel::GroupHiddenRole).toBool(), false); } // set SearchFor group hidden m_places->setGroupHidden(KFilePlacesModel::SearchForType, true); for (auto groupType : {KFilePlacesModel::PlacesType, KFilePlacesModel::RemoteType, KFilePlacesModel::RecentlySavedType, KFilePlacesModel::SearchForType, KFilePlacesModel::DevicesType, KFilePlacesModel::RemovableDevicesType}) { const bool groupShouldBeHidden = (groupType == KFilePlacesModel::SearchForType); for (auto index : m_places->groupIndexes(groupType)) { QCOMPARE(index.data(KFilePlacesModel::GroupHiddenRole).toBool(), groupShouldBeHidden); } } // set SearchFor group visible again m_places->setGroupHidden(KFilePlacesModel::SearchForType, false); for (int r = 0, rMax = m_places->rowCount(); r < rMax; r++) { const QModelIndex index = m_places->index(r, 0); QCOMPARE(index.data(KFilePlacesModel::GroupHiddenRole).toBool(), false); } } void KFilePlacesModelTest::testFilterWithAlternativeApplicationName() { const QStringList urls = initialListOfUrls(); const QString alternativeApplicationName = QStringLiteral("kfile_places_model_test"); KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(bookmarksFile(), QStringLiteral("kfilePlaces")); KBookmarkGroup root = bookmarkManager->root(); // create a new entry with alternative application name KBookmark bookmark = root.addBookmark(QStringLiteral("Extra entry"), QUrl(QStringLiteral("search:/videos-alternative")), {}); const QString id = QUuid::createUuid().toString(); bookmark.setMetaDataItem(QStringLiteral("ID"), id); bookmark.setMetaDataItem(QStringLiteral("OnlyInApp"), alternativeApplicationName); bookmarkManager->emitChanged(bookmarkManager->root()); // make sure that the entry is not visible on the original model CHECK_PLACES_URLS(urls); // create a new model with alternativeApplicationName KFilePlacesModel *newModel = new KFilePlacesModel(alternativeApplicationName); QTRY_COMPARE(placesUrls(newModel).count(QStringLiteral("search:/videos-alternative")), 1); delete newModel; } void KFilePlacesModelTest::testSupportedSchemes() { QCoreApplication::processEvents(); // support running this test on its own QCOMPARE(m_places->supportedSchemes(), QStringList()); QCOMPARE(placesUrls(), initialListOfUrls()); m_places->setSupportedSchemes({"trash"}); QCOMPARE(m_places->supportedSchemes(), QStringList("trash")); QCOMPARE(placesUrls(), QStringList("trash:/")); m_places->setSupportedSchemes({}); QCOMPARE(m_places->supportedSchemes(), QStringList()); QCOMPARE(placesUrls(), initialListOfUrls()); } QTEST_MAIN(KFilePlacesModelTest) #include "kfileplacesmodeltest.moc" diff --git a/src/filewidgets/kfileplacesmodel.cpp b/src/filewidgets/kfileplacesmodel.cpp index 8194d645..842aaa67 100644 --- a/src/filewidgets/kfileplacesmodel.cpp +++ b/src/filewidgets/kfileplacesmodel.cpp @@ -1,1278 +1,1278 @@ /* This file is part of the KDE project Copyright (C) 2007 Kevin Ottens Copyright (C) 2007 David Faure This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kfileplacesmodel.h" #include "kfileplacesitem_p.h" #ifdef _WIN32_WCE #include "Windows.h" #include "WinBase.h" #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { QString stateNameForGroupType(KFilePlacesModel::GroupType type) { switch (type) { case KFilePlacesModel::PlacesType: return QStringLiteral("GroupState-Places-IsHidden"); case KFilePlacesModel::RemoteType: return QStringLiteral("GroupState-Remote-IsHidden"); case KFilePlacesModel::RecentlySavedType: return QStringLiteral("GroupState-RecentlySaved-IsHidden"); case KFilePlacesModel::SearchForType: return QStringLiteral("GroupState-SearchFor-IsHidden"); case KFilePlacesModel::DevicesType: return QStringLiteral("GroupState-Devices-IsHidden"); case KFilePlacesModel::RemovableDevicesType: return QStringLiteral("GroupState-RemovableDevices-IsHidden"); default: Q_UNREACHABLE(); } } static bool isFileIndexingEnabled() { KConfig config(QStringLiteral("baloofilerc")); KConfigGroup basicSettings = config.group("Basic Settings"); return basicSettings.readEntry("Indexing-Enabled", true); } static QString timelineDateString(int year, int month, int day = 0) { const QString dateFormat("%1-%2"); QString date = dateFormat.arg(year).arg(month, 2, 10, QChar('0')); if (day > 0) { date += QString("-%1").arg(day, 2, 10, QChar('0')); } return date; } static QUrl createTimelineUrl(const QUrl &url) { // based on dolphin urls const QString timelinePrefix = QStringLiteral("timeline:") + QLatin1Char('/'); QUrl timelineUrl; const QString path = url.toDisplayString(QUrl::PreferLocalFile); if (path.endsWith(QLatin1String("/yesterday"))) { const QDate date = QDate::currentDate().addDays(-1); const int year = date.year(); const int month = date.month(); const int day = date.day(); timelineUrl = QUrl(timelinePrefix + timelineDateString(year, month) + '/' + timelineDateString(year, month, day)); } else if (path.endsWith(QLatin1String("/thismonth"))) { const QDate date = QDate::currentDate(); timelineUrl = QUrl(timelinePrefix + timelineDateString(date.year(), date.month())); } else if (path.endsWith(QLatin1String("/lastmonth"))) { const QDate date = QDate::currentDate().addMonths(-1); timelineUrl = QUrl(timelinePrefix + timelineDateString(date.year(), date.month())); } else { Q_ASSERT(path.endsWith(QLatin1String("/today"))); timelineUrl = url; } return timelineUrl; } static QUrl createSearchUrl(const QUrl &url) { QUrl searchUrl = url; const QString path = url.toDisplayString(QUrl::PreferLocalFile); const QStringList validSearchPaths = { QStringLiteral("/documents"), QStringLiteral("/images"), QStringLiteral("/audio"), QStringLiteral("/videos") }; for (const QString &validPath : validSearchPaths) { if (path.endsWith(validPath)) { searchUrl.setScheme(QStringLiteral("baloosearch")); return searchUrl; } } qWarning() << "Invalid search url:" << url; return searchUrl; } } class Q_DECL_HIDDEN KFilePlacesModel::Private { public: Private(KFilePlacesModel *self) : q(self), bookmarkManager(nullptr), fileIndexingEnabled(isFileIndexingEnabled()) { } ~Private() { qDeleteAll(items); } KFilePlacesModel *q; QList items; QVector availableDevices; QMap setupInProgress; QStringList supportedSchemes; Solid::Predicate predicate; KBookmarkManager *bookmarkManager; const bool fileIndexingEnabled; QString alternativeApplicationName; void reloadAndSignal(); QList loadBookmarkList(); int findNearestPosition(int source, int target); void _k_initDeviceList(); void _k_deviceAdded(const QString &udi); void _k_deviceRemoved(const QString &udi); void _k_itemChanged(const QString &udi); void _k_reloadBookmarks(); void _k_storageSetupDone(Solid::ErrorType error, QVariant errorData); void _k_storageTeardownDone(Solid::ErrorType error, QVariant errorData); private: bool isBalooUrl(const QUrl &url) const; }; KFilePlacesModel::KFilePlacesModel(const QString &alternativeApplicationName, QObject *parent) : QAbstractItemModel(parent), d(new Private(this)) { const QString file = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/user-places.xbel"; d->bookmarkManager = KBookmarkManager::managerForExternalFile(file); d->alternativeApplicationName = alternativeApplicationName; // Let's put some places in there if it's empty. KBookmarkGroup root = d->bookmarkManager->root(); const auto setDefaultMetadataItemForGroup = [&root](KFilePlacesModel::GroupType type) { root.setMetaDataItem(stateNameForGroupType(type), QStringLiteral("false")); }; if (root.first().isNull() || !QFile::exists(file)) { // NOTE: The context for these I18N_NOOP2 calls has to be "KFile System Bookmarks". // The real i18nc call is made later, with this context, so the two must match. // // createSystemBookmark actually does nothing with its third argument, // but we have to give it something so the I18N_NOOP2 calls stay here for now. // // (coles, 13th May 2009) KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Home"), I18N_NOOP2("KFile System Bookmarks", "Home"), QUrl::fromLocalFile(QDir::homePath()), QStringLiteral("user-home")); // Some distros may not create various standard XDG folders by default // so check for their existance before adding bookmarks for them const QString desktopFolder = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); if (QDir(desktopFolder).exists()) { KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Desktop"), I18N_NOOP2("KFile System Bookmarks", "Desktop"), QUrl::fromLocalFile(desktopFolder), QStringLiteral("user-desktop")); } const QString downloadFolder = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation); if (QDir(downloadFolder).exists()) { KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Downloads"), I18N_NOOP2("KFile System Bookmarks", "Downloads"), QUrl::fromLocalFile(downloadFolder), QStringLiteral("folder-downloads")); } KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Network"), I18N_NOOP2("KFile System Bookmarks", "Network"), - QUrl(QStringLiteral("remote:/")), QStringLiteral("network-workgroup")); + QUrl(QStringLiteral("remote:/")), QStringLiteral("folder-network")); #if defined(_WIN32_WCE) // adding drives foreach (const QFileInfo &info, QDir::drives()) { QString driveIcon = "drive-harddisk"; KFilePlacesItem::createSystemBookmark(d->bookmarkManager, info.absoluteFilePath(), info.absoluteFilePath(), QUrl::fromLocalFile(info.absoluteFilePath()), driveIcon); } #elif !defined(Q_OS_WIN) KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Root"), I18N_NOOP2("KFile System Bookmarks", "Root"), QUrl::fromLocalFile(QStringLiteral("/")), QStringLiteral("folder-red")); #endif KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Trash"), I18N_NOOP2("KFile System Bookmarks", "Trash"), QUrl(QStringLiteral("trash:/")), QStringLiteral("user-trash")); setDefaultMetadataItemForGroup(PlacesType); setDefaultMetadataItemForGroup(RemoteType); setDefaultMetadataItemForGroup(DevicesType); setDefaultMetadataItemForGroup(RemovableDevicesType); // Force bookmarks to be saved. If on open/save dialog and the bookmarks are not saved, QFile::exists // will always return false, which opening/closing all the time the open/save dialog would case the // bookmarks to be added once each time, having lots of times each bookmark. (ereslibre) d->bookmarkManager->saveAs(file); } // if baloo is enabled, add new urls even if the bookmark file is not empty if (d->fileIndexingEnabled && root.metaDataItem(QStringLiteral("withBaloo")) != QLatin1String("true")) { root.setMetaDataItem(QStringLiteral("withBaloo"), QStringLiteral("true")); KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Today"), I18N_NOOP2("KFile System Bookmarks", "Today"), QUrl(QStringLiteral("timeline:/today")), QStringLiteral("go-jump-today")); KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Yesterday"), I18N_NOOP2("KFile System Bookmarks", "Yesterday"), QUrl(QStringLiteral("timeline:/yesterday")), QStringLiteral("view-calendar-day")); KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Documents"), I18N_NOOP2("KFile System Bookmarks", "Documents"), QUrl(QStringLiteral("search:/documents")), QStringLiteral("folder-text")); KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Images"), I18N_NOOP2("KFile System Bookmarks", "Images"), QUrl(QStringLiteral("search:/images")), QStringLiteral("folder-images")); KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Audio Files"), I18N_NOOP2("KFile System Bookmarks", "Audio Files"), QUrl(QStringLiteral("search:/audio")), QStringLiteral("folder-sound")); KFilePlacesItem::createSystemBookmark(d->bookmarkManager, QStringLiteral("Videos"), I18N_NOOP2("KFile System Bookmarks", "Videos"), QUrl(QStringLiteral("search:/videos")), QStringLiteral("folder-videos")); setDefaultMetadataItemForGroup(SearchForType); setDefaultMetadataItemForGroup(RecentlySavedType); d->bookmarkManager->save(); } QString predicate(QString::fromLatin1("[[[[ 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 ]")); if (KProtocolInfo::isKnownProtocol(QStringLiteral("mtp"))) { predicate.prepend("["); predicate.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']"); } d->predicate = Solid::Predicate::fromString(predicate); Q_ASSERT(d->predicate.isValid()); connect(d->bookmarkManager, SIGNAL(changed(QString,QString)), this, SLOT(_k_reloadBookmarks())); connect(d->bookmarkManager, SIGNAL(bookmarksChanged(QString)), this, SLOT(_k_reloadBookmarks())); d->_k_reloadBookmarks(); QTimer::singleShot(0, this, SLOT(_k_initDeviceList())); } KFilePlacesModel::KFilePlacesModel(QObject *parent) : KFilePlacesModel({}, parent) { } KFilePlacesModel::~KFilePlacesModel() { delete d; } QUrl KFilePlacesModel::url(const QModelIndex &index) const { return data(index, UrlRole).toUrl(); } bool KFilePlacesModel::setupNeeded(const QModelIndex &index) const { return data(index, SetupNeededRole).toBool(); } QIcon KFilePlacesModel::icon(const QModelIndex &index) const { return data(index, Qt::DecorationRole).value(); } QString KFilePlacesModel::text(const QModelIndex &index) const { return data(index, Qt::DisplayRole).toString(); } bool KFilePlacesModel::isHidden(const QModelIndex &index) const { //Note: we do not want to show an index if its parent is hidden return data(index, HiddenRole).toBool() || isGroupHidden(index); } bool KFilePlacesModel::isGroupHidden(const GroupType type) const { const QString hidden = d->bookmarkManager->root().metaDataItem(stateNameForGroupType(type)); return hidden == QStringLiteral("true") ? true : false; } bool KFilePlacesModel::isGroupHidden(const QModelIndex &index) const { if (!index.isValid()) { return false; } KFilePlacesItem *item = static_cast(index.internalPointer()); return isGroupHidden(item->groupType()); } bool KFilePlacesModel::isDevice(const QModelIndex &index) const { if (!index.isValid()) { return false; } KFilePlacesItem *item = static_cast(index.internalPointer()); return item->isDevice(); } Solid::Device KFilePlacesModel::deviceForIndex(const QModelIndex &index) const { if (!index.isValid()) { return Solid::Device(); } KFilePlacesItem *item = static_cast(index.internalPointer()); if (item->isDevice()) { return item->device(); } else { return Solid::Device(); } } KBookmark KFilePlacesModel::bookmarkForIndex(const QModelIndex &index) const { if (!index.isValid()) { return KBookmark(); } KFilePlacesItem *item = static_cast(index.internalPointer()); return item->bookmark(); } KFilePlacesModel::GroupType KFilePlacesModel::groupType(const QModelIndex &index) const { if (!index.isValid()) { return UnknownType; } KFilePlacesItem *item = static_cast(index.internalPointer()); return item->groupType(); } QModelIndexList KFilePlacesModel::groupIndexes(const KFilePlacesModel::GroupType type) const { if (type == UnknownType) { return QModelIndexList(); } QModelIndexList indexes; const int rows = rowCount(); for (int row = 0; row < rows ; ++row) { const QModelIndex current = index(row, 0); if (groupType(current) == type) { indexes << current; } } return indexes; } QVariant KFilePlacesModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } KFilePlacesItem *item = static_cast(index.internalPointer()); if (role == KFilePlacesModel::GroupHiddenRole) { return isGroupHidden(item->groupType()); } else { return item->data(role); } } QModelIndex KFilePlacesModel::index(int row, int column, const QModelIndex &parent) const { if (row < 0 || column != 0 || row >= d->items.size()) { return QModelIndex(); } if (parent.isValid()) { return QModelIndex(); } return createIndex(row, column, d->items.at(row)); } QModelIndex KFilePlacesModel::parent(const QModelIndex &child) const { Q_UNUSED(child); return QModelIndex(); } int KFilePlacesModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) { return 0; } else { return d->items.size(); } } int KFilePlacesModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) // We only know 1 piece of information for a particular entry return 1; } QModelIndex KFilePlacesModel::closestItem(const QUrl &url) const { int foundRow = -1; int maxLength = 0; // Search the item which is equal to the URL or at least is a parent URL. // If there are more than one possible item URL candidates, choose the item // which covers the bigger range of the URL. for (int row = 0; row < d->items.size(); ++row) { KFilePlacesItem *item = d->items[row]; const QUrl itemUrl(item->data(UrlRole).toUrl()); if (itemUrl.matches(url, QUrl::StripTrailingSlash) || itemUrl.isParentOf(url)) { const int length = itemUrl.toString().length(); if (length > maxLength) { foundRow = row; maxLength = length; } } } if (foundRow == -1) { return QModelIndex(); } else { return createIndex(foundRow, 0, d->items[foundRow]); } } void KFilePlacesModel::Private::_k_initDeviceList() { Solid::DeviceNotifier *notifier = Solid::DeviceNotifier::instance(); connect(notifier, SIGNAL(deviceAdded(QString)), q, SLOT(_k_deviceAdded(QString))); connect(notifier, SIGNAL(deviceRemoved(QString)), q, SLOT(_k_deviceRemoved(QString))); const QList &deviceList = Solid::Device::listFromQuery(predicate); foreach (const Solid::Device &device, deviceList) { availableDevices << device.udi(); } _k_reloadBookmarks(); } void KFilePlacesModel::Private::_k_deviceAdded(const QString &udi) { Solid::Device d(udi); if (predicate.matches(d)) { availableDevices << udi; _k_reloadBookmarks(); } } void KFilePlacesModel::Private::_k_deviceRemoved(const QString &udi) { auto it = std::find(availableDevices.begin(), availableDevices.end(), udi); if (it != availableDevices.end()) { availableDevices.erase(it); _k_reloadBookmarks(); } } void KFilePlacesModel::Private::_k_itemChanged(const QString &id) { for (int row = 0; row < items.size(); ++row) { if (items.at(row)->id() == id) { QModelIndex index = q->index(row, 0); emit q->dataChanged(index, index); } } } void KFilePlacesModel::Private::_k_reloadBookmarks() { QList currentItems = loadBookmarkList(); QList::Iterator it_i = items.begin(); QList::Iterator it_c = currentItems.begin(); QList::Iterator end_i = items.end(); QList::Iterator end_c = currentItems.end(); while (it_i != end_i || it_c != end_c) { if (it_i == end_i && it_c != end_c) { int row = items.count(); q->beginInsertRows(QModelIndex(), row, row); it_i = items.insert(it_i, *it_c); ++it_i; it_c = currentItems.erase(it_c); end_i = items.end(); end_c = currentItems.end(); q->endInsertRows(); } else if (it_i != end_i && it_c == end_c) { int row = items.indexOf(*it_i); q->beginRemoveRows(QModelIndex(), row, row); delete *it_i; it_i = items.erase(it_i); end_i = items.end(); end_c = currentItems.end(); q->endRemoveRows(); } else if ((*it_i)->id() == (*it_c)->id()) { bool shouldEmit = !((*it_i)->bookmark() == (*it_c)->bookmark()); (*it_i)->setBookmark((*it_c)->bookmark()); if (shouldEmit) { int row = items.indexOf(*it_i); QModelIndex idx = q->index(row, 0); emit q->dataChanged(idx, idx); } ++it_i; ++it_c; } else if ((*it_i)->id() != (*it_c)->id()) { int row = items.indexOf(*it_i); if (it_i + 1 != end_i && (*(it_i + 1))->id() == (*it_c)->id()) { // if the next one matches, it's a remove q->beginRemoveRows(QModelIndex(), row, row); delete *it_i; it_i = items.erase(it_i); end_i = items.end(); end_c = currentItems.end(); q->endRemoveRows(); } else { q->beginInsertRows(QModelIndex(), row, row); it_i = items.insert(it_i, *it_c); ++it_i; it_c = currentItems.erase(it_c); end_i = items.end(); end_c = currentItems.end(); q->endInsertRows(); } } } qDeleteAll(currentItems); currentItems.clear(); } bool KFilePlacesModel::Private::isBalooUrl(const QUrl &url) const { const QString scheme = url.scheme(); return ((scheme == QLatin1String("timeline")) || (scheme == QLatin1String("search"))); } QList KFilePlacesModel::Private::loadBookmarkList() { QList items; KBookmarkGroup root = bookmarkManager->root(); KBookmark bookmark = root.first(); QVector devices = availableDevices; while (!bookmark.isNull()) { if (bookmark.url().isValid()) { QString udi = bookmark.metaDataItem(QStringLiteral("UDI")); QString appName = bookmark.metaDataItem(QStringLiteral("OnlyInApp")); QUrl url = bookmark.url(); auto it = std::find(devices.begin(), devices.end(), udi); bool deviceAvailable = (it != devices.end()); if (deviceAvailable) { devices.erase(it); } bool allowedHere = appName.isEmpty() || ((appName == QCoreApplication::instance()->applicationName()) || (appName == alternativeApplicationName)); bool isSupportedUrl = isBalooUrl(url) ? fileIndexingEnabled : true; bool isSupportedScheme = supportedSchemes.isEmpty() || supportedSchemes.contains(url.scheme()); if (isSupportedScheme && ((isSupportedUrl && udi.isEmpty() && allowedHere) || deviceAvailable)) { KFilePlacesItem *item; if (deviceAvailable) { item = new KFilePlacesItem(bookmarkManager, bookmark.address(), udi); // TODO: Update bookmark internal element } else { item = new KFilePlacesItem(bookmarkManager, bookmark.address()); } connect(item, SIGNAL(itemChanged(QString)), q, SLOT(_k_itemChanged(QString))); items << item; } } bookmark = root.next(bookmark); } // Add bookmarks for the remaining devices, they were previously unknown foreach (const QString &udi, devices) { bookmark = KFilePlacesItem::createDeviceBookmark(bookmarkManager, udi); if (!bookmark.isNull()) { KFilePlacesItem *item = new KFilePlacesItem(bookmarkManager, bookmark.address(), udi); connect(item, SIGNAL(itemChanged(QString)), q, SLOT(_k_itemChanged(QString))); // TODO: Update bookmark internal element items << item; } } // return a sorted list based on groups qStableSort(items.begin(), items.end(), [](KFilePlacesItem *itemA, KFilePlacesItem *itemB) { return (itemA->groupType() < itemB->groupType()); }); return items; } int KFilePlacesModel::Private::findNearestPosition(int source, int target) { const KFilePlacesItem *item = items.at(source); const KFilePlacesModel::GroupType groupType = item->groupType(); int newTarget = qMin(target, items.count() - 1); // moving inside the same group is ok if ((items.at(newTarget)->groupType() == groupType)) { return target; } if (target > source) { // moving down, move it to the end of the group int groupFooter = source; while (items.at(groupFooter)->groupType() == groupType) { groupFooter++; // end of the list move it there if (groupFooter == items.count()) { break; } } target = groupFooter; } else { // moving up, move it to beginning of the group int groupHead = source; while (items.at(groupHead)->groupType() == groupType) { groupHead--; // beginning of the list move it there if (groupHead == 0) { break; } } target = groupHead; } return target; } void KFilePlacesModel::Private::reloadAndSignal() { bookmarkManager->emitChanged(bookmarkManager->root()); // ... we'll get relisted anyway } Qt::DropActions KFilePlacesModel::supportedDropActions() const { return Qt::ActionMask; } Qt::ItemFlags KFilePlacesModel::flags(const QModelIndex &index) const { Qt::ItemFlags res = Qt::ItemIsSelectable | Qt::ItemIsEnabled; if (index.isValid()) { res |= Qt::ItemIsDragEnabled; } if (!index.isValid()) { res |= Qt::ItemIsDropEnabled; } return res; } static QString _k_internalMimetype(const KFilePlacesModel *const self) { return QStringLiteral("application/x-kfileplacesmodel-") + QString::number(reinterpret_cast(self)); } QStringList KFilePlacesModel::mimeTypes() const { QStringList types; types << _k_internalMimetype(this) << QStringLiteral("text/uri-list"); return types; } QMimeData *KFilePlacesModel::mimeData(const QModelIndexList &indexes) const { QList urls; QByteArray itemData; QDataStream stream(&itemData, QIODevice::WriteOnly); foreach (const QModelIndex &index, indexes) { QUrl itemUrl = url(index); if (itemUrl.isValid()) { urls << itemUrl; } stream << index.row(); } QMimeData *mimeData = new QMimeData(); if (!urls.isEmpty()) { mimeData->setUrls(urls); } mimeData->setData(_k_internalMimetype(this), itemData); return mimeData; } bool KFilePlacesModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { if (action == Qt::IgnoreAction) { return true; } if (column > 0) { return false; } if (row == -1 && parent.isValid()) { return false; // Don't allow to move an item onto another one, // too easy for the user to mess something up // If we really really want to allow copying files this way, // let's do it in the views to get the good old drop menu } if (data->hasFormat(_k_internalMimetype(this))) { // The operation is an internal move QByteArray itemData = data->data(_k_internalMimetype(this)); QDataStream stream(&itemData, QIODevice::ReadOnly); int itemRow; stream >> itemRow; if (!movePlace(itemRow, row)) { return false; } } else if (data->hasFormat(QStringLiteral("text/uri-list"))) { // The operation is an add QMimeDatabase db; KBookmark afterBookmark; if (row == -1) { // The dropped item is moved or added to the last position KFilePlacesItem *lastItem = d->items.last(); afterBookmark = lastItem->bookmark(); } else { // The dropped item is moved or added before position 'row', ie after position 'row-1' if (row > 0) { KFilePlacesItem *afterItem = d->items[row - 1]; afterBookmark = afterItem->bookmark(); } } const QList urls = KUrlMimeData::urlsFromMimeData(data); KBookmarkGroup group = d->bookmarkManager->root(); foreach (const QUrl &url, urls) { // TODO: use KIO::stat in order to get the UDS_DISPLAY_NAME too KIO::MimetypeJob *job = KIO::mimetype(url); QString mimeString; if (!job->exec()) { mimeString = QStringLiteral("unknown"); } else { mimeString = job->mimetype(); } QMimeType mimetype = db.mimeTypeForName(mimeString); if (!mimetype.isValid()) { qWarning() << "URL not added to Places as mimetype could not be determined!"; continue; } if (!mimetype.inherits(QStringLiteral("inode/directory"))) { // Only directories are allowed continue; } KFileItem item(url, mimetype.name(), S_IFDIR); KBookmark bookmark = KFilePlacesItem::createBookmark(d->bookmarkManager, url.fileName(), url, item.iconName()); group.moveBookmark(bookmark, afterBookmark); afterBookmark = bookmark; } } else { // Oops, shouldn't happen thanks to mimeTypes() qWarning() << ": received wrong mimedata, " << data->formats(); return false; } refresh(); return true; } void KFilePlacesModel::refresh() const { d->reloadAndSignal(); } QUrl KFilePlacesModel::convertedUrl(const QUrl &url) { QUrl newUrl = url; if (url.scheme() == QLatin1String("timeline")) { newUrl = createTimelineUrl(url); } else if (url.scheme() == QLatin1String("search")) { newUrl = createSearchUrl(url); } return newUrl; } void KFilePlacesModel::addPlace(const QString &text, const QUrl &url, const QString &iconName, const QString &appName) { addPlace(text, url, iconName, appName, QModelIndex()); } void KFilePlacesModel::addPlace(const QString &text, const QUrl &url, const QString &iconName, const QString &appName, const QModelIndex &after) { KBookmark bookmark = KFilePlacesItem::createBookmark(d->bookmarkManager, text, url, iconName); if (!appName.isEmpty()) { bookmark.setMetaDataItem(QStringLiteral("OnlyInApp"), appName); } if (after.isValid()) { KFilePlacesItem *item = static_cast(after.internalPointer()); d->bookmarkManager->root().moveBookmark(bookmark, item->bookmark()); } refresh(); } void KFilePlacesModel::editPlace(const QModelIndex &index, const QString &text, const QUrl &url, const QString &iconName, const QString &appName) { if (!index.isValid()) { return; } KFilePlacesItem *item = static_cast(index.internalPointer()); if (item->isDevice()) { return; } KBookmark bookmark = item->bookmark(); if (bookmark.isNull()) { return; } bool changed = false; if (text != bookmark.fullText()) { bookmark.setFullText(text); changed = true; } if (url != bookmark.url()) { bookmark.setUrl(url); changed = true; } if (iconName != bookmark.icon()) { bookmark.setIcon(iconName); changed = true; } const QString onlyInApp = bookmark.metaDataItem(QStringLiteral("OnlyInApp")); if (appName != onlyInApp) { bookmark.setMetaDataItem(QStringLiteral("OnlyInApp"), appName); changed = true; } if (changed) { refresh(); emit dataChanged(index, index); } } void KFilePlacesModel::removePlace(const QModelIndex &index) const { if (!index.isValid()) { return; } KFilePlacesItem *item = static_cast(index.internalPointer()); if (item->isDevice()) { return; } KBookmark bookmark = item->bookmark(); if (bookmark.isNull()) { return; } d->bookmarkManager->root().deleteBookmark(bookmark); refresh(); } void KFilePlacesModel::setPlaceHidden(const QModelIndex &index, bool hidden) { if (!index.isValid()) { return; } KFilePlacesItem *item = static_cast(index.internalPointer()); if (item->bookmark().isNull() || item->isHidden() == hidden) { return; } const bool groupHidden = isGroupHidden(item->groupType()); const bool hidingChildOnShownParent = hidden && !groupHidden; const bool showingChildOnShownParent = !hidden && !groupHidden; if (hidingChildOnShownParent || showingChildOnShownParent) { item->setHidden(hidden); d->reloadAndSignal(); emit dataChanged(index, index); } } void KFilePlacesModel::setGroupHidden(const GroupType type, bool hidden) { if (isGroupHidden(type) == hidden) return; d->bookmarkManager->root().setMetaDataItem(stateNameForGroupType(type), (hidden ? QStringLiteral("true") : QStringLiteral("false"))); d->reloadAndSignal(); emit groupHiddenChanged(type, hidden); } bool KFilePlacesModel::movePlace(int itemRow, int row) { KBookmark afterBookmark; if ((itemRow < 0) || (itemRow >= d->items.count())) { return false; } if (row >= d->items.count()) { row = -1; } if (row == -1) { // The dropped item is moved or added to the last position KFilePlacesItem *lastItem = d->items.last(); afterBookmark = lastItem->bookmark(); } else { // The dropped item is moved or added before position 'row', ie after position 'row-1' if (row > 0) { KFilePlacesItem *afterItem = d->items[row - 1]; afterBookmark = afterItem->bookmark(); } } KFilePlacesItem *item = d->items[itemRow]; KBookmark bookmark = item->bookmark(); int destRow = row == -1 ? d->items.count() : row; // avoid move item away from its group destRow = d->findNearestPosition(itemRow, destRow); // The item is not moved when the drop indicator is on either item edge if (itemRow == destRow || itemRow + 1 == destRow) { return false; } beginMoveRows(QModelIndex(), itemRow, itemRow, QModelIndex(), destRow); d->bookmarkManager->root().moveBookmark(bookmark, afterBookmark); // Move item ourselves so that _k_reloadBookmarks() does not consider // the move as a remove + insert. // // 2nd argument of QList::move() expects the final destination index, // but 'row' is the value of the destination index before the moved // item has been removed from its original position. That is why we // adjust if necessary. d->items.move(itemRow, itemRow < destRow ? (destRow - 1) : destRow); endMoveRows(); return true; } int KFilePlacesModel::hiddenCount() const { int rows = rowCount(); int hidden = 0; for (int i = 0; i < rows; ++i) { if (isHidden(index(i, 0))) { hidden++; } } return hidden; } QAction *KFilePlacesModel::teardownActionForIndex(const QModelIndex &index) const { Solid::Device device = deviceForIndex(index); if (device.is() && device.as()->isAccessible()) { Solid::StorageDrive *drive = device.as(); if (drive == nullptr) { drive = device.parent().as(); } bool hotpluggable = false; bool removable = false; if (drive != nullptr) { hotpluggable = drive->isHotpluggable(); removable = drive->isRemovable(); } QString iconName; QString text; QString label = data(index, Qt::DisplayRole).toString().replace('&', QLatin1String("&&")); if (device.is()) { text = i18n("&Release '%1'", label); } else if (removable || hotpluggable) { text = i18n("&Safely Remove '%1'", label); iconName = QStringLiteral("media-eject"); } else { text = i18n("&Unmount '%1'", label); iconName = QStringLiteral("media-eject"); } if (!iconName.isEmpty()) { return new QAction(QIcon::fromTheme(iconName), text, nullptr); } else { return new QAction(text, nullptr); } } return nullptr; } QAction *KFilePlacesModel::ejectActionForIndex(const QModelIndex &index) const { Solid::Device device = deviceForIndex(index); if (device.is()) { QString label = data(index, Qt::DisplayRole).toString().replace('&', QLatin1String("&&")); QString text = i18n("&Eject '%1'", label); return new QAction(QIcon::fromTheme(QStringLiteral("media-eject")), text, nullptr); } return nullptr; } void KFilePlacesModel::requestTeardown(const QModelIndex &index) { Solid::Device device = deviceForIndex(index); Solid::StorageAccess *access = device.as(); if (access != nullptr) { connect(access, SIGNAL(teardownDone(Solid::ErrorType,QVariant,QString)), this, SLOT(_k_storageTeardownDone(Solid::ErrorType,QVariant))); access->teardown(); } } void KFilePlacesModel::requestEject(const QModelIndex &index) { Solid::Device device = deviceForIndex(index); Solid::OpticalDrive *drive = device.parent().as(); if (drive != nullptr) { connect(drive, SIGNAL(ejectDone(Solid::ErrorType,QVariant,QString)), this, SLOT(_k_storageTeardownDone(Solid::ErrorType,QVariant))); drive->eject(); } else { QString label = data(index, Qt::DisplayRole).toString().replace('&', QLatin1String("&&")); QString message = i18n("The device '%1' is not a disk and cannot be ejected.", label); emit errorMessage(message); } } void KFilePlacesModel::requestSetup(const QModelIndex &index) { Solid::Device device = deviceForIndex(index); if (device.is() && !d->setupInProgress.contains(device.as()) && !device.as()->isAccessible()) { Solid::StorageAccess *access = device.as(); d->setupInProgress[access] = index; connect(access, SIGNAL(setupDone(Solid::ErrorType,QVariant,QString)), this, SLOT(_k_storageSetupDone(Solid::ErrorType,QVariant))); access->setup(); } } void KFilePlacesModel::Private::_k_storageSetupDone(Solid::ErrorType error, QVariant errorData) { QPersistentModelIndex index = setupInProgress.take(q->sender()); if (!index.isValid()) { return; } if (!error) { emit q->setupDone(index, true); } else { if (errorData.isValid()) { emit q->errorMessage(i18n("An error occurred while accessing '%1', the system responded: %2", q->text(index), errorData.toString())); } else { emit q->errorMessage(i18n("An error occurred while accessing '%1'", q->text(index))); } emit q->setupDone(index, false); } } void KFilePlacesModel::Private::_k_storageTeardownDone(Solid::ErrorType error, QVariant errorData) { if (error && errorData.isValid()) { emit q->errorMessage(errorData.toString()); } } void KFilePlacesModel::setSupportedSchemes(const QStringList &schemes) { d->supportedSchemes = schemes; d->_k_reloadBookmarks(); } QStringList KFilePlacesModel::supportedSchemes() const { return d->supportedSchemes; } #include "moc_kfileplacesmodel.cpp"