aboutsummaryrefslogtreecommitdiffstats
path: root/examples/quickcontrols/filesystemexplorer/filesystemmodel.cpp
blob: b580bced055180b1f6c612869a3ba01f6cd19f36 (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
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "filesystemmodel.h"

#include <QStandardPaths>
#include <QMimeDatabase>
#include <QTextDocument>
#include <QTextObject>

FileSystemModel::FileSystemModel(QObject *parent) : QFileSystemModel(parent)
{
    setFilter(QDir::AllEntries | QDir::Hidden | QDir::NoDotAndDotDot);
    setInitialDirectory();
}

QString FileSystemModel::readFile(const QString &filePath)
{
    // Don't issue errors for an empty path, as the initial binding
    // will result in an empty path, and that's OK.
    if (filePath.isEmpty())
        return {};

    QFile file(filePath);

    if (file.size() >= 2'000'000)
        return tr("File size is too big.\nYou can read files up to %1 MB.").arg(2);

    static const QMimeDatabase db;
    const QMimeType mime = db.mimeTypeForFile(QFileInfo(file));

    // Check if the mimetype is supported and return the content.
    const auto mimeTypesForFile = mime.parentMimeTypes();
    for (const auto &m : mimeTypesForFile) {
        if (m.contains("text", Qt::CaseInsensitive)
                || mime.comment().contains("text", Qt::CaseInsensitive)) {
            if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                return tr("Error opening the File!");

            QTextStream stream(&file);
            return stream.readAll();
        }
    }
    return tr("Filetype not supported!");
}

// This function gets called from Editor.qml
int FileSystemModel::currentLineNumber(QQuickTextDocument *textDocument, int cursorPosition)
{
    if (QTextDocument *td = textDocument->textDocument()) {
        QTextBlock tb = td->findBlock(cursorPosition);
        return tb.blockNumber();
    }
    return -1;
}

int FileSystemModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return 1;
}

QModelIndex FileSystemModel::rootIndex() const
{
    return m_rootIndex;
}

void FileSystemModel::setRootIndex(const QModelIndex index)
{
    if (index == m_rootIndex)
        return;
    m_rootIndex = index;
    emit rootIndexChanged();
}

void FileSystemModel::setInitialDirectory(const QString &path)
{
    QDir dir(path);
    if (dir.makeAbsolute())
        setRootPath(dir.path());
    else
        setRootPath(getDefaultRootDir());
    setRootIndex(QFileSystemModel::index(dir.path(), 0));
}

QString FileSystemModel::getDefaultRootDir()
{
    return QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
}