Browse Source

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.
Emanuel Sprung 5 years ago
parent
commit
4d50398f02
2 changed files with 47 additions and 0 deletions
  1. 43 0
      Libraries/LibGUI/JsonArrayModel.cpp
  2. 4 0
      Libraries/LibGUI/JsonArrayModel.h

+ 43 - 0
Libraries/LibGUI/JsonArrayModel.cpp

@@ -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()));

+ 4 - 0
Libraries/LibGUI/JsonArrayModel.h

@@ -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)