From 187d7cb4001fd0820d5eef53aeb593fb0db25802 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Thu, 7 Mar 2019 17:06:11 +0100 Subject: [PATCH] GTextEditor: Add write_to_file(String path) :^) --- Applications/TextEditor/main.cpp | 5 +++-- LibGUI/GTextEditor.cpp | 35 ++++++++++++++++++++++++++++++++ LibGUI/GTextEditor.h | 2 ++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/Applications/TextEditor/main.cpp b/Applications/TextEditor/main.cpp index 2180e4db32..1fd5e3e3b8 100644 --- a/Applications/TextEditor/main.cpp +++ b/Applications/TextEditor/main.cpp @@ -66,8 +66,9 @@ int main(int argc, char** argv) dbgprintf("FIXME: Implement File/Open"); }); - auto save_action = GAction::create("Save document", { Mod_Ctrl, Key_S }, GraphicsBitmap::load_from_file(GraphicsBitmap::Format::RGBA32, "/res/icons/save16.rgb", { 16, 16 }), [] (const GAction&) { - dbgprintf("FIXME: Implement File/Save"); + auto save_action = GAction::create("Save document", { Mod_Ctrl, Key_S }, GraphicsBitmap::load_from_file(GraphicsBitmap::Format::RGBA32, "/res/icons/save16.rgb", { 16, 16 }), [&] (const GAction&) { + dbgprintf("Writing document to '%s'\n", path.characters()); + text_editor->write_to_file(path); }); auto menubar = make(); diff --git a/LibGUI/GTextEditor.cpp b/LibGUI/GTextEditor.cpp index 72d6321735..1cf4dcc5b7 100644 --- a/LibGUI/GTextEditor.cpp +++ b/LibGUI/GTextEditor.cpp @@ -3,6 +3,9 @@ #include #include #include +#include +#include +#include GTextEditor::GTextEditor(GWidget* parent) : GWidget(parent) @@ -429,3 +432,35 @@ void GTextEditor::Line::truncate(int length) m_text.resize(length + 1); m_text.last() = 0; } + +bool GTextEditor::write_to_file(const String& path) +{ + int fd = open(path.characters(), O_WRONLY | O_CREAT, 0666); + if (fd < 0) { + perror("open"); + return false; + } + for (int i = 0; i < m_lines.size(); ++i) { + auto& line = *m_lines[i]; + if (line.length()) { + ssize_t nwritten = write(fd, line.characters(), line.length()); + if (nwritten < 0) { + perror("write"); + close(fd); + return false; + } + } + if (i != m_lines.size() - 1) { + char ch = '\n'; + ssize_t nwritten = write(fd, &ch, 1); + if (nwritten != 1) { + perror("write"); + close(fd); + return false; + } + } + } + + close(fd); + return true; +} diff --git a/LibGUI/GTextEditor.h b/LibGUI/GTextEditor.h index 1c905512b2..a390d87da6 100644 --- a/LibGUI/GTextEditor.h +++ b/LibGUI/GTextEditor.h @@ -49,6 +49,8 @@ public: GTextPosition cursor() const { return m_cursor; } int glyph_width() const { return font().glyph_width('x'); } + bool write_to_file(const String& path); + private: virtual void paint_event(GPaintEvent&) override; virtual void resize_event(GResizeEvent&) override;