summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLucas CHOLLET <lucas.chollet@free.fr>2023-01-07 11:52:46 -0500
committerSam Atkins <atkinssj@gmail.com>2023-01-07 19:53:35 +0000
commitcf1eea27d3757fe0208065f05663a1b601e37f31 (patch)
treefd39f8c0027aa67a3e781ac02e6e46d7dc84e0dd
parent72b144e9e92605d48c83d6ad568add588ab0d32e (diff)
downloadserenity-cf1eea27d3757fe0208065f05663a1b601e37f31.zip
LibGUI: Add `TextEditor::write_to_file(Core::Stream::File&)`
This overload use the `Core::Stream` API instead of the now deprecated one `Core::File`.
-rw-r--r--Userland/Libraries/LibGUI/TextEditor.cpp27
-rw-r--r--Userland/Libraries/LibGUI/TextEditor.h1
2 files changed, 28 insertions, 0 deletions
diff --git a/Userland/Libraries/LibGUI/TextEditor.cpp b/Userland/Libraries/LibGUI/TextEditor.cpp
index b75d851b10..3236d3c5fc 100644
--- a/Userland/Libraries/LibGUI/TextEditor.cpp
+++ b/Userland/Libraries/LibGUI/TextEditor.cpp
@@ -1512,6 +1512,33 @@ bool TextEditor::write_to_file(Core::File& file)
return true;
}
+ErrorOr<void> TextEditor::write_to_file(Core::Stream::File& file)
+{
+ off_t file_size = 0;
+ if (line_count() == 1 && line(0).is_empty()) {
+ // Truncate to zero.
+ } else {
+ // Compute the final file size and ftruncate() to make writing fast.
+ // FIXME: Remove this once the kernel is smart enough to do this instead.
+ for (size_t i = 0; i < line_count(); ++i)
+ file_size += line(i).length();
+ file_size += line_count();
+ }
+
+ TRY(file.truncate(file_size));
+
+ if (file_size == 0) {
+ // A size 0 file doesn't need a data copy.
+ } else {
+ for (size_t i = 0; i < line_count(); ++i) {
+ TRY(file.write(line(i).to_utf8().bytes()));
+ TRY(file.write("\n"sv.bytes()));
+ }
+ }
+ document().set_unmodified();
+ return {};
+}
+
DeprecatedString TextEditor::text() const
{
return document().text();
diff --git a/Userland/Libraries/LibGUI/TextEditor.h b/Userland/Libraries/LibGUI/TextEditor.h
index fe51519593..f5586d000b 100644
--- a/Userland/Libraries/LibGUI/TextEditor.h
+++ b/Userland/Libraries/LibGUI/TextEditor.h
@@ -131,6 +131,7 @@ public:
void replace_all_text_without_resetting_undo_stack(StringView text);
bool write_to_file(DeprecatedString const& path);
bool write_to_file(Core::File&);
+ ErrorOr<void> write_to_file(Core::Stream::File&);
bool has_selection() const { return m_selection.is_valid(); }
DeprecatedString selected_text() const;
size_t number_of_words() const;