LibGUI: Add store(), add() and remove() methods to JsonArrayModel

This patchset adds the methods to alter an JSON model and store it back
to the disk.
This commit is contained in:
Emanuel Sprung 2020-03-26 20:01:23 +01:00 committed by Andreas Kling
parent 337ade9e4c
commit 4d50398f02
Notes: sideshowbarker 2024-07-19 08:06:18 +09:00
2 changed files with 47 additions and 0 deletions

View file

@ -48,6 +48,49 @@ void JsonArrayModel::update()
did_update();
}
bool JsonArrayModel::store()
{
auto file = Core::File::construct(m_json_path);
if (!file->open(Core::IODevice::WriteOnly)) {
dbg() << "Unable to open " << file->filename();
return false;
}
file->write(m_array.to_string());
file->close();
return true;
}
bool JsonArrayModel::add(const Vector<JsonValue>&& values)
{
ASSERT(values.size() == m_fields.size());
JsonObject obj;
for (size_t i = 0; i < m_fields.size(); ++i) {
auto& field_spec = m_fields[i];
obj.set(field_spec.json_field_name, values.at(i));
}
m_array.append(move(obj));
did_update();
return true;
}
bool JsonArrayModel::remove(int row)
{
if (row >= m_array.size())
return false;
JsonArray new_array;
for (int i = 0; i < m_array.size(); ++i)
if (i != row)
new_array.append(m_array.at(i));
m_array = new_array;
did_update();
return true;
}
Model::ColumnMetadata JsonArrayModel::column_metadata(int column) const
{
ASSERT(column < static_cast<int>(m_fields.size()));

View file

@ -76,6 +76,10 @@ public:
const String& json_path() const { return m_json_path; }
void set_json_path(const String& json_path);
bool add(const Vector<JsonValue>&& fields);
bool remove(int row);
bool store();
private:
JsonArrayModel(const String& json_path, Vector<FieldSpec>&& fields)
: m_json_path(json_path)