File indexing completed on 2024-05-19 16:17:12
0001 // SPDX-FileCopyrightText: 2023 Mathis BrĂ¼chert <mbb@kaidan.im> 0002 // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL 0003 0004 #include "notesmodel.h" 0005 #include <QDateTime> 0006 #include <QDebug> 0007 #include <QFile> 0008 #include <QStandardPaths> 0009 #include <QUrl> 0010 0011 NotesModel::NotesModel(QObject *parent) 0012 : QAbstractListModel(parent) 0013 { 0014 } 0015 0016 int NotesModel::rowCount(const QModelIndex &index) const 0017 { 0018 return m_path.isEmpty() ? 0 : directory.entryList(QDir::Files).count(); 0019 } 0020 0021 QVariant NotesModel::data(const QModelIndex &index, int role) const 0022 { 0023 switch (role) { 0024 case Role::Path: 0025 return QUrl::fromLocalFile(directory.entryInfoList(QDir::Files).at(index.row()).filePath()); 0026 case Role::Date: 0027 return directory.entryInfoList(QDir::Files).at(index.row()).birthTime(); 0028 case Role::Name: 0029 return directory.entryInfoList(QDir::Files).at(index.row()).fileName().replace(".md", ""); 0030 } 0031 0032 Q_UNREACHABLE(); 0033 0034 return {}; 0035 } 0036 0037 QHash<int, QByteArray> NotesModel::roleNames() const 0038 { 0039 return {{Role::Date, "date"}, {Role::Path, "path"}, {Role::Name, "name"}}; 0040 } 0041 0042 void NotesModel::addNote(const QString &name) 0043 { 0044 beginResetModel(); 0045 QFile file(m_path + QDir::separator() + name + ".md"); 0046 if (file.open(QFile::WriteOnly)) { 0047 file.write(""); 0048 } else { 0049 qDebug() << "Failed to create file at" << m_path; 0050 } 0051 endResetModel(); 0052 } 0053 0054 void NotesModel::deleteNote(const QUrl &path) 0055 { 0056 beginResetModel(); 0057 QFile::remove(path.toLocalFile()); 0058 endResetModel(); 0059 } 0060 0061 void NotesModel::renameNote(const QUrl &path, const QString &name) 0062 { 0063 QString newPath = directory.path() + QDir::separator() + name + ".md"; 0064 beginResetModel(); 0065 QFile::rename(path.toLocalFile(), newPath); 0066 endResetModel(); 0067 } 0068 0069 QString NotesModel::path() const 0070 { 0071 return m_path; 0072 } 0073 0074 void NotesModel::setPath(const QString &newPath) 0075 { 0076 if (m_path == newPath) 0077 return; 0078 0079 beginResetModel(); 0080 m_path = newPath; 0081 directory = QDir(m_path); 0082 endResetModel(); 0083 Q_EMIT pathChanged(); 0084 }