diff --git a/src/file.cpp b/src/file.cpp index 4b63288..774d902 100644 --- a/src/file.cpp +++ b/src/file.cpp @@ -2,6 +2,8 @@ #include +constexpr std::string_view TEMPORARY_EXTENSION = ".tmp"; + File::File(const std::filesystem::path& path, const char* mode) { open(path, mode); @@ -73,11 +75,17 @@ bool file_text_load(const std::filesystem::path& path, std::string* output, cons } } -bool file_text_save(const std::filesystem::path& path, std::string_view data, const char* mode) +bool file_text_save(const std::filesystem::path& path, std::string_view data) { - File file(path, mode); - if (!file) - return false; - - return std::fwrite(data.data(), 1, data.size(), file.get()) == data.size(); + auto temporaryPath = path; + temporaryPath += TEMPORARY_EXTENSION; + File file(temporaryPath, "wb"); + auto isWritten = file && std::fwrite(data.data(), 1, data.size(), file.get()) == data.size(); + isWritten = file.close() == 0 && isWritten; + std::error_code error; + if (isWritten) + std::filesystem::rename(temporaryPath, path, error); + if (!isWritten || error) + std::filesystem::remove(temporaryPath, error); + return isWritten && !error; } diff --git a/src/file.h b/src/file.h index e35069e..c8697ae 100644 --- a/src/file.h +++ b/src/file.h @@ -21,4 +21,5 @@ private: }; bool file_text_load(const std::filesystem::path&, std::string*, const char* mode = "rb"); -bool file_text_save(const std::filesystem::path&, std::string_view, const char* mode = "wb"); +// Written to a temporary file beside it, then renamed over it: a failed or cut-short write leaves the old file whole. +bool file_text_save(const std::filesystem::path&, std::string_view); diff --git a/src/framebuffer.cpp b/src/framebuffer.cpp index 2864131..b00cbf1 100644 --- a/src/framebuffer.cpp +++ b/src/framebuffer.cpp @@ -29,7 +29,6 @@ void Framebuffer::set() gl.FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); - gl.BindFramebuffer(GL_FRAMEBUFFER, 0); } @@ -43,7 +42,7 @@ void Framebuffer::size_set(Vec2 size) std::vector Framebuffer::pixels_get() const { - auto count = size.x * size.y * IMAGE_CHANNELS; + auto count = (std::size_t)size.x * (std::size_t)size.y * IMAGE_CHANNELS; std::vector pixels(count); gl.ReadBuffer(GL_COLOR_ATTACHMENT0); diff --git a/src/image.cpp b/src/image.cpp index d04ba09..4c79362 100644 --- a/src/image.cpp +++ b/src/image.cpp @@ -142,7 +142,7 @@ Image Image::vector_render(float scale) const size_t Image::pixel_size_get() const { - return size.x * size.y * IMAGE_CHANNELS; + return (size_t)size.x * (size_t)size.y * IMAGE_CHANNELS; } Image::Image(const uint8_t* data, IVec2 size, bool isLinear) : isLinear(isLinear) @@ -191,16 +191,12 @@ bool Image::write_pixels_png(const std::filesystem::path& path, IVec2 size, cons if (!data || size.x <= 0 || size.y <= 0) return false; - File file(path, "wb"); - if (auto handle = file.get()) - { - auto write_func = [](void* context, void* bytes, int count) { - fwrite(bytes, 1, count, static_cast(context)); - }; - return stbi_write_png_to_func(write_func, handle, size.x, size.y, IMAGE_CHANNELS, data, - size.x * IMAGE_CHANNELS) != 0; - } - return false; + std::string png; + auto write_func = [](void* context, void* bytes, int count) { + ((std::string*)context)->append((char*)bytes, count); + }; + return stbi_write_png_to_func(write_func, &png, size.x, size.y, IMAGE_CHANNELS, data, size.x * IMAGE_CHANNELS) && + file_text_save(path, png); } // Copies a size-sized block between images. Pixels outside either image are skipped. diff --git a/src/manager.cpp b/src/manager.cpp index a285462..614ee22 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -70,7 +70,7 @@ static void path_list_save(const std::filesystem::path& path, const std::vector< std::ostringstream file; for (auto& entry : entries) file << path_to_utf8(entry) << '\n'; - if (!file_text_save(path, file.str(), "wb")) + if (!file_text_save(path, file.str())) logger.warning(std::format("Could not write {} to: {}. Skipping...", name, path_to_utf8(path))); } diff --git a/src/model/xml.cpp b/src/model/xml.cpp index d8893b5..8dcd2d7 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -1837,15 +1837,7 @@ bool model_load_string(Model& model, std::string_view text, std::string* errorSt bool model_save(const Model& model, const std::filesystem::path& path, std::string* errorString, Options options) { - auto text = model_to_string(model, options); - File file(path, "wb"); - if (!file) - { - if (errorString) - *errorString = "File permissions."; - return false; - } - if (std::fwrite(text.data(), 1, text.size(), file.get()) == text.size()) + if (file_text_save(path, model_to_string(model, options))) return true; if (errorString) *errorString = "Could not write the file."; diff --git a/src/render.cpp b/src/render.cpp index e62e1b3..c885d4d 100644 --- a/src/render.cpp +++ b/src/render.cpp @@ -65,7 +65,7 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy auto data = (const char*)audio.data(); auto byteCount = audio.size() * sizeof(float); - if (file_text_save(audioPath, std::string_view(data, byteCount), "wb")) + if (file_text_save(audioPath, std::string_view(data, byteCount))) { auto audioDurationFilter = std::string{}; auto frameCount = (double)std::max((int)framePaths.size(), 1); @@ -187,9 +187,13 @@ static std::filesystem::path frame_filename_get(const std::filesystem::path& for auto fallback = path_from_utf8(std::format("frame_{:06}.png", index)); if (type != RENDER_PNGS) return fallback; + // A format without a placeholder numbers its frames after its name. + auto formatUtf8 = path_to_utf8(format); + if (formatUtf8.find('{') == std::string::npos) + formatUtf8 = path_to_utf8(format.stem()) + "_{:06}" + path_to_utf8(format.extension()); try { - auto filename = path_from_utf8(std::vformat(path_to_utf8(format), std::make_format_args(index))).filename(); + auto filename = path_from_utf8(std::vformat(formatUtf8, std::make_format_args(index))).filename(); if (filename.empty()) return fallback; if (filename.extension().empty()) @@ -313,6 +317,7 @@ bool Recorder::start(const RecorderOptions& recorderOptions) count = frame_count_get(options.start, options.end, options.animationFps, options.fps); frames.clear(); sounds.clear(); + soundCopies.clear(); soundTime = -1; directory = frames_directory_create(options); return !directory.empty(); @@ -337,6 +342,8 @@ bool Recorder::is_sound_frame() const bool Recorder::frame_capture(std::vector pixels, IVec2 size, std::vector frameSounds) { soundTime = (int)std::floor(time_get()); + for (auto& sound : frameSounds) + sound = &soundCopies.try_emplace(sound->uid, *sound).first->second; sounds.push_back(std::move(frameSounds)); if (options.isIsolated || options.isBounded) pixels_unpremultiply(pixels); @@ -348,12 +355,13 @@ bool Recorder::frame_capture(std::vector pixels, IVec2 size, std::vecto return true; } -void Recorder::finish() +bool Recorder::finish() { auto pathString = path_to_utf8(options.path); + auto isFinished = !frames.empty(); if (options.type == RENDER_PNGS) - toast_log(frames.empty() ? Level::ERROR : Level::INFO, - frames.empty() ? TOAST_EXPORT_RENDERED_FRAMES_FAILED : TOAST_EXPORT_RENDERED_FRAMES, pathString); + toast_log(isFinished ? Level::INFO : Level::ERROR, + isFinished ? TOAST_EXPORT_RENDERED_FRAMES : TOAST_EXPORT_RENDERED_FRAMES_FAILED, pathString); else if (options.type == RENDER_SPRITESHEET) { auto layout = spritesheet_layout_get(options.rows, options.columns, (int)frames.size()); @@ -361,7 +369,10 @@ void Recorder::finish() if (frames.empty()) toast_log(Level::WARNING, TOAST_SPRITESHEET_NO_FRAMES); else if (!first.is_valid()) + { + isFinished = false; toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY); + } else { Image sheet = {}; @@ -370,20 +381,21 @@ void Recorder::finish() for (int i = 0; i < (int)frames.size() && i < layout.rows * layout.columns; ++i) if (auto frame = Image(frames[i]); frame.size == first.size) sheet.paste(frame, first.size * IVec2(i % layout.columns, i / layout.columns)); - auto isSaved = sheet.write_png(options.path); - toast_log(isSaved ? Level::INFO : Level::ERROR, - isSaved ? TOAST_EXPORT_SPRITESHEET : TOAST_EXPORT_SPRITESHEET_FAILED, pathString); + isFinished = sheet.write_png(options.path); + toast_log(isFinished ? Level::INFO : Level::ERROR, + isFinished ? TOAST_EXPORT_SPRITESHEET : TOAST_EXPORT_SPRITESHEET_FAILED, pathString); } } else { auto audio = options.isSound && options.type != RENDER_GIF ? audio_mix(sounds, options.fps) : std::vector(); - auto isRendered = animation_render(options.ffmpegPath, options.path, frames, audio, options.type, options.fps); - toast_log(isRendered ? Level::INFO : Level::ERROR, - isRendered ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); + isFinished = animation_render(options.ffmpegPath, options.path, frames, audio, options.type, options.fps); + toast_log(isFinished ? Level::INFO : Level::ERROR, + isFinished ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); } cancel(); + return isFinished; } // Stops. The temporary frame folder is removed (a PNG sequence's own folder is kept). @@ -395,6 +407,7 @@ void Recorder::cancel() directory.clear(); frames.clear(); sounds.clear(); + soundCopies.clear(); index = count = 0; } @@ -415,8 +428,7 @@ bool animation_record(const RecorderOptions& recorderOptions, Canvas& canvas, Sh recorder.cancel(); return false; } - recorder.finish(); - return is_path_exist(options.path); + return recorder.finish(); } constexpr float BAKE_MARGIN = 1.0f; diff --git a/src/render.h b/src/render.h index 50f698d..3d1a4fb 100644 --- a/src/render.h +++ b/src/render.h @@ -3,6 +3,7 @@ #include #include #include +#include #include #include "audio_data.h" @@ -170,13 +171,16 @@ public: float time_get() const; bool is_sound_frame() const; bool frame_capture(std::vector, IVec2, std::vector = {}); - void finish(); + // False when the output couldn't be made. + bool finish(); void cancel(); private: std::filesystem::path directory; std::vector frames; + // Each frame's trigger sounds, pointing into soundCopies (by uid), so they outlive a reload during the render. std::vector> sounds; + std::map soundCopies; int soundTime = -1; }; diff --git a/src/settings.cpp b/src/settings.cpp index 5a3ea01..f7a05d3 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -322,7 +322,7 @@ void Settings::save(const std::filesystem::path& path, const std::string& imguiD logger.error(std::format("Failed while writing settings file: {}", pathUtf8)); return; } - if (!file_text_save(path, file.str(), "wb")) + if (!file_text_save(path, file.str())) { logger.error(std::format("Failed to save settings file: {}", pathUtf8)); return; diff --git a/tests/assets.cpp b/tests/assets.cpp index 64b64ba..a3c07ac 100644 --- a/tests/assets.cpp +++ b/tests/assets.cpp @@ -2,6 +2,7 @@ #include "asset_store.h" #include "audio_data.h" +#include "file.h" #include "font.h" #include "friends.h" #include "icon.h" @@ -135,3 +136,18 @@ TEST_CASE("Embedded resources load") for (auto& font : FONTS) CHECK(font->size > 0); } + +TEST_CASE("a save replaces its file whole, or leaves it as it was") +{ + auto path = std::filesystem::temp_directory_path() / "anm2ed_save_test.txt"; + auto text = std::string{}; + REQUIRE(file_text_save(path, "first")); + CHECK(file_text_save(path, "second")); + CHECK(file_text_load(path, &text)); + CHECK(text == "second"); + CHECK_FALSE(file_text_save(path / "inside_a_file.txt", "third")); + CHECK(file_text_load(path, &text)); + CHECK(text == "second"); + CHECK_FALSE(std::filesystem::exists(path.string() + ".tmp")); + std::filesystem::remove(path); +} diff --git a/tests/render/render.cpp b/tests/render/render.cpp index a69f331..103d45b 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -6,7 +6,6 @@ #include #include -#include #include #include "audio.h" @@ -133,6 +132,31 @@ TEST_CASE("a recorded spritesheet holds every frame") golden_image_check("spin_sheet.png"); } +TEST_CASE("a PNG sequence without a placeholder numbers each frame") +{ + RenderFixture fixture("spin.anm2"); + if (!fixture.gl.is_valid()) + { + MESSAGE("skipped: no OpenGL context"); + return; + } + + auto directory = OUTPUT_DIR / "spin_sequence"; + std::filesystem::remove_all(directory); + RecorderOptions options{.type = RENDER_PNGS, + .path = directory, + .format = "spin.png", + .start = 0, + .end = fixture.animation->frameNum - 1, + .animationFps = fixture.document->model.info.fps, + .fps = fixture.document->model.info.fps}; + REQUIRE(animation_record(options, *fixture.canvas, *fixture.shader, *fixture.document, *fixture.animation, + fixture.bounds, SCALE, BACKGROUND, true)); + auto count = std::ranges::distance(std::filesystem::directory_iterator(directory)); + CHECK(count == fixture.animation->frameNum); + CHECK(std::filesystem::exists(directory / "spin_000000.png")); +} + TEST_CASE("animation layers draw their child animations") { RenderFixture fixture("nested.anm2");