PixelPaint: Display an error message if saving to PP file fails

This commit is contained in:
Andreas Kling 2021-06-14 21:46:29 +02:00
parent fa7bb98b1e
commit c333aec9f3
Notes: sideshowbarker 2024-07-18 12:14:16 +09:00
3 changed files with 17 additions and 10 deletions

View file

@ -12,6 +12,7 @@
#include <AK/JsonValue.h>
#include <AK/MappedFile.h>
#include <AK/StringBuilder.h>
#include <LibCore/File.h>
#include <LibGUI/Painter.h>
#include <LibGfx/BMPWriter.h>
#include <LibGfx/Bitmap.h>
@ -140,9 +141,8 @@ RefPtr<Image> Image::try_create_from_file(String const& file_path)
return Image::try_create_from_bitmap(bitmap.release_nonnull());
}
void Image::save(String const& file_path) const
Result<void, String> Image::write_to_file(const String& file_path) const
{
// Build json file
StringBuilder builder;
JsonObjectSerializer json(builder);
json.add("width", m_size.width());
@ -165,11 +165,13 @@ void Image::save(String const& file_path) const
}
json.finish();
// Write json to disk
auto file = fopen(file_path.characters(), "w");
auto byte_buffer = builder.to_byte_buffer();
fwrite(byte_buffer.data(), sizeof(u8), byte_buffer.size(), file);
fclose(file);
auto file_or_error = Core::File::open(file_path, (Core::OpenMode)(Core::OpenMode::WriteOnly | Core::OpenMode::Truncate));
if (file_or_error.is_error())
return file_or_error.error();
if (!file_or_error.value()->write(builder.string_view()))
return String { file_or_error.value()->error_string() };
return {};
}
void Image::export_bmp(String const& file_path)

View file

@ -10,6 +10,7 @@
#include <AK/NonnullRefPtrVector.h>
#include <AK/RefCounted.h>
#include <AK/RefPtr.h>
#include <AK/Result.h>
#include <AK/Vector.h>
#include <LibGUI/Command.h>
#include <LibGUI/Forward.h>
@ -52,7 +53,7 @@ public:
void restore_snapshot(Image const&);
void paint_into(GUI::Painter&, Gfx::IntRect const& dest_rect);
void save(String const& file_path) const;
Result<void, String> write_to_file(String const& file_path) const;
void export_bmp(String const& file_path);
void export_png(String const& file_path);

View file

@ -115,10 +115,14 @@ int main(int argc, char** argv)
auto save_image_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
if (!image_editor.image())
return;
Optional<String> save_path = GUI::FilePicker::get_save_filepath(window, "untitled", "pp");
auto save_path = GUI::FilePicker::get_save_filepath(window, "untitled", "pp");
if (!save_path.has_value())
return;
image_editor.image()->save(save_path.value());
auto result = image_editor.image()->write_to_file(save_path.value());
if (result.is_error()) {
GUI::MessageBox::show_error(window, String::formatted("Could not save {}: {}", save_path.value(), result.error()));
return;
}
});
auto menubar = GUI::Menubar::construct();