partitionmodel.cpp 12.7 KB
Newer Older
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
/*
 * Copyright (C) 2016 Jolla Ltd. <andrew.den.exter@jolla.com>
 *
 * You may use this file under the terms of the BSD license as follows:
 *
 * "Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *   * Neither the name of Nemo Mobile nor the names of its contributors
 *     may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
 */

#include "partitionmodel.h"
#include "partitionmanager_p.h"

35 36 37 38
#include "logging_p.h"

#include <QDir>
#include <QFileInfo>
39
#include <QtQml/qqmlinfo.h>
40

41 42 43 44 45 46 47 48 49 50
PartitionModel::PartitionModel(QObject *parent)
    : QAbstractListModel(parent)
    , m_manager(PartitionManagerPrivate::instance())
    , m_storageTypes(Any | ExcludeParents)
{
    m_partitions = m_manager->partitions(Partition::Any | Partition::ExcludeParents);

    connect(m_manager.data(), &PartitionManagerPrivate::partitionChanged, this, &PartitionModel::partitionChanged);
    connect(m_manager.data(), &PartitionManagerPrivate::partitionAdded, this, &PartitionModel::partitionAdded);
    connect(m_manager.data(), &PartitionManagerPrivate::partitionRemoved, this, &PartitionModel::partitionRemoved);
51 52
    connect(m_manager.data(), &PartitionManagerPrivate::externalStoragesPopulatedChanged,
            this, &PartitionModel::externalStoragesPopulatedChanged);
53 54 55

    connect(m_manager.data(), &PartitionManagerPrivate::errorMessage, this, &PartitionModel::errorMessage);

56 57 58 59 60 61 62
    connect(m_manager.data(), &PartitionManagerPrivate::lockError, this, [this](Partition::Error error) {
        emit lockError(static_cast<PartitionModel::Error>(error));
    });
    connect(m_manager.data(), &PartitionManagerPrivate::unlockError, this, [this](Partition::Error error) {
        emit unlockError(static_cast<PartitionModel::Error>(error));
    });

63 64 65 66 67 68 69 70 71
    connect(m_manager.data(), &PartitionManagerPrivate::mountError, this, [this](Partition::Error error) {
        emit mountError(static_cast<PartitionModel::Error>(error));
    });
    connect(m_manager.data(), &PartitionManagerPrivate::unmountError, this, [this](Partition::Error error) {
        emit unmountError(static_cast<PartitionModel::Error>(error));
    });
    connect(m_manager.data(), &PartitionManagerPrivate::formatError, this, [this](Partition::Error error) {
        emit formatError(static_cast<PartitionModel::Error>(error));
    });
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
}

PartitionModel::~PartitionModel()
{
}

PartitionModel::StorageTypes PartitionModel::storageTypes() const
{
    return m_storageTypes;
}

void PartitionModel::setStorageTypes(StorageTypes types)
{
    if (m_storageTypes != types) {
        m_storageTypes = types;

        update();

        emit storageTypesChanged();
    }
}

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
QStringList PartitionModel::supportedFormatTypes() const
{
    QStringList types;
    QDir dir("/sbin/");
    QStringList entries = dir.entryList(QStringList() << QString("mkfs.*"));
    for (const QString &entry : entries) {
        QFileInfo info(QString("/sbin/%1").arg(entry));
        if (info.exists() && info.isExecutable()) {
            QStringList parts = entry.split('.');
            if (!parts.isEmpty()) {
                types << parts.takeLast();
            }
        }
    }

    return types;
}

112 113 114 115 116
bool PartitionModel::externalStoragesPopulated() const
{
    return m_manager->externalStoragesPopulated();
}

117 118 119 120 121 122 123 124 125 126 127 128
void PartitionModel::refresh()
{
    m_manager->refresh();
}

void PartitionModel::refresh(int index)
{
    if (index >= 0 && index < m_partitions.count()) {
        m_partitions[index].refresh();
    }
}

129
void PartitionModel::lock(const QString &devicePath)
130
{
131
    qCInfo(lcMemoryCardLog) << Q_FUNC_INFO << devicePath << m_partitions.count();
132
    m_manager->lock(devicePath);
133 134
}

135
void PartitionModel::unlock(const QString &devicePath, const QString &passphrase)
136
{
137 138
    qCInfo(lcMemoryCardLog) << Q_FUNC_INFO << devicePath << m_partitions.count();
    if (const Partition *partition = getPartition(devicePath)) {
139 140
        m_manager->unlock(*partition, passphrase);
    } else {
141
        qCWarning(lcMemoryCardLog) << "Unable to unlock unknown device:" << devicePath;
142 143 144
    }
}

145
void PartitionModel::mount(const QString &devicePath)
146
{
147 148
    qCInfo(lcMemoryCardLog) << Q_FUNC_INFO << devicePath << m_partitions.count();
    if (const Partition *partition = getPartition(devicePath)) {
149 150
        m_manager->mount(*partition);
    } else {
151
        qCWarning(lcMemoryCardLog) << "Unable to mount unknown device:" << devicePath;
152
    }
153 154
}

155
void PartitionModel::unmount(const QString &devicePath)
156
{
157 158
    qCInfo(lcMemoryCardLog) << Q_FUNC_INFO << devicePath << m_partitions.count();
    if (const Partition *partition = getPartition(devicePath)) {
159 160
        m_manager->unmount(*partition);
    } else {
161
        qCWarning(lcMemoryCardLog) << "Unable to unmount unknown device:" << devicePath;
162
    }
163 164
}

165
void PartitionModel::format(const QString &devicePath, const QVariantMap &arguments)
166
{
167 168
    QString filesystemType = arguments.value(QLatin1String("filesystemType"), QString()).toString();
    if (filesystemType.isEmpty()) {
169 170 171 172 173 174 175 176 177
        qmlInfo(this) << "Missing or empty filesystemType argument, cannot format.";
        return;
    }

    // Only fixing invalid args would be enough. Udisks don't care if key is unknown like auto-mount.
    QVariantMap args;
    args.insert(QLatin1String("label"), arguments.value(QLatin1String("label"), QString()).toString());
    args.insert(QLatin1String("no-block"), true);
    args.insert(QLatin1String("take-ownership"), true);
178 179
    // set-group-permissions is a custom option patched into udisks2 (JB#50288)
    args.insert(QLatin1String("set-group-permissions"), true);
180 181 182 183 184 185 186 187
    args.insert(QLatin1String("update-partition-type"), true);
    args.insert(QLatin1String("auto-mount"), arguments.value(QLatin1String("auto-mount"), false).toBool());

    QString passphrase = arguments.value(QLatin1String("encrypt-passphrase"), QString()).toString();
    if (!passphrase.isEmpty()) {
        args.insert(QLatin1String("encrypt.passphrase"), passphrase);
    }

188 189
    qCInfo(lcMemoryCardLog) << Q_FUNC_INFO << devicePath << filesystemType << args << m_partitions.count();
    m_manager->format(devicePath, filesystemType, args);
190 191
}

192
QString PartitionModel::objectPath(const QString &devicePath) const
193
{
194
    qCInfo(lcMemoryCardLog) << Q_FUNC_INFO << devicePath;
195
    return m_manager->objectPath(devicePath);
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
void PartitionModel::update()
{
    const int count = m_partitions.count();

    const auto partitions = m_manager->partitions(Partition::StorageTypes(int(m_storageTypes)));

    int index = 0;

    for (const auto partition : partitions) {
        const int existingIndex = [this, index, partition]() {
            for (int i = index; i < m_partitions.count(); ++i) {
                if (m_partitions.at(i) == partition) {
                    return i;
                }
            }
            return -1;
        }();

        if (existingIndex == -1) {
            beginInsertRows(QModelIndex(), index, index);
            m_partitions.insert(index, partition);
            endInsertRows();
        } else if (existingIndex > index) {
            beginMoveRows(QModelIndex(), existingIndex, existingIndex, QModelIndex(), index);
            const auto partition = m_partitions.takeAt(existingIndex);
            m_partitions.insert(index, partition);
            endMoveRows();
        }
        ++index;
    }

    if (index < m_partitions.count()) {
        beginRemoveRows(QModelIndex(), index, m_partitions.count() - 1);
        m_partitions.resize(index);
        endRemoveRows();
    }

    if (count != m_partitions.count()) {
        emit countChanged();
    }
}

240
const Partition *PartitionModel::getPartition(const QString &devicePath) const
241 242
{
    for (const Partition &partition : m_partitions) {
243
        if (devicePath == partition.devicePath()) {
244 245 246 247 248 249 250
            return &partition;
        }
    }

    return nullptr;
}

251 252 253 254 255 256 257 258 259
QHash<int, QByteArray> PartitionModel::roleNames() const
{
    static const QHash<int, QByteArray> roleNames = {
        { ReadOnlyRole, "readOnly" },
        { StatusRole, "status" },
        { CanMountRole, "canMount" },
        { MountFailedRole, "mountFailed" },
        { StorageTypeRole, "storageType" },
        { FilesystemTypeRole, "filesystemType" },
260
        { DeviceLabelRole, "deviceLabel" },
261
        { DevicePathRole, "devicePath" },
262
        { DeviceNameRole, "deviceName" },
263 264 265
        { MountPathRole, "mountPath" },
        { BytesAvailableRole, "bytesAvailable" },
        { BytesTotalRole, "bytesTotal" },
266
        { BytesFreeRole, "bytesFree" },
267 268
        { PartitionModelRole, "partitionModel" },
        { IsCryptoDeviceRoles, "isCryptoDevice"},
269
        { IsSupportedFileSystemType, "isSupportedFileSystemType"},
270
        { IsEncryptedRoles, "isEncrypted"},
271
        { CryptoBackingDevicePath, "cryptoBackingDevicePath"},
272
        { DriveRole, "drive"},
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
    };

    return roleNames;
}

int PartitionModel::rowCount(const QModelIndex &parent) const
{
    return !parent.isValid() ? m_partitions.count() : 0;
}

QVariant PartitionModel::data(const QModelIndex &index, int role) const
{
    if (index.row() < 0 || index.row() >= m_partitions.count() || index.column() != 0) {
        return QVariant();
    } else {
        const Partition &partition = m_partitions.at(index.row());

        switch (role) {
        case ReadOnlyRole:
            return partition.isReadOnly();
        case StatusRole:
            return partition.status();
        case CanMountRole:
            return partition.canMount();
        case MountFailedRole:
            return partition.mountFailed();
        case StorageTypeRole:
            return partition.storageType();
        case FilesystemTypeRole:
            return partition.filesystemType();
303 304
        case DeviceLabelRole:
            return partition.deviceLabel();
305 306
        case DevicePathRole:
            return partition.devicePath();
307 308
        case DeviceNameRole:
            return partition.deviceName();
309 310 311 312 313 314 315 316
        case MountPathRole:
            return partition.mountPath();
        case BytesAvailableRole:
            return partition.bytesAvailable();
        case BytesTotalRole:
            return partition.bytesTotal();
        case BytesFreeRole:
            return partition.bytesFree();
317 318
        case PartitionModelRole:
            return QVariant::fromValue(static_cast<QObject*>(const_cast<PartitionModel*>((this))));
319 320
        case IsCryptoDeviceRoles:
            return partition.isCryptoDevice();
321 322
        case IsSupportedFileSystemType:
            return partition.isSupportedFileSystemType();
323 324
        case IsEncryptedRoles:
            return partition.isEncrypted();
325 326
        case CryptoBackingDevicePath:
            return partition.cryptoBackingDevicePath();
327 328
        case DriveRole:
            return partition.drive();
329 330 331 332 333 334 335 336 337
        default:
            return QVariant();
        }
    }
}

void PartitionModel::partitionChanged(const Partition &partition)
{
    for (int i = 0; i < m_partitions.count(); ++i) {
338
        qCInfo(lcMemoryCardLog) << "partition changed:" << partition.status() << partition.mountPath();;
339
        if (m_partitions.at(i) == partition) {
340 341
            QModelIndex index = createIndex(i, 0);
            emit dataChanged(index, index);
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
            return;
        }
    }
}

void PartitionModel::partitionAdded(const Partition &partition)
{
    if (partition.storageType() & m_storageTypes) {
        update();
    }
}

void PartitionModel::partitionRemoved(const Partition &partition)
{
    for (int i = 0; i < m_partitions.count(); ++i) {
        if (m_partitions.at(i) == partition) {
            beginRemoveRows(QModelIndex(), i, i);
            m_partitions.removeAt(i);
            endRemoveRows();

            emit countChanged();

            return;
        }
    }
}