From 5e27111b21aef4db127ac73e64df076a5295cc75 Mon Sep 17 00:00:00 2001 From: shweet Date: Thu, 13 Aug 2026 21:40:28 -0400 Subject: [PATCH] address log accumulation issue and non-ascii files load on program init --- src/dialog.cpp | 6 +- src/dialog.hpp | 3 +- src/imgui/actions.hpp | 1 + src/imgui/window/timeline.cpp | 42 +-- src/imgui/window/window.cpp | 617 ++++++++++++++++++++++++++++++---- src/log.cpp | 142 +++++++- src/log.hpp | 5 +- src/main.cpp | 94 +++++- src/render.cpp | 14 +- src/resource/strings.hpp | 10 + src/settings.cpp | 27 +- src/settings.hpp | 3 + 12 files changed, 811 insertions(+), 153 deletions(-) diff --git a/src/dialog.cpp b/src/dialog.cpp index 9f8f4b8..542d868 100644 --- a/src/dialog.cpp +++ b/src/dialog.cpp @@ -55,13 +55,15 @@ namespace anm2ed this->type = type; } - void Dialog::file_save(Type type) + void Dialog::file_save(Type type, const std::filesystem::path& defaultPath) { if (type == Dialog::NONE) return; path.clear(); paths.clear(); + auto defaultPathString = path::to_utf8(defaultPath); + auto defaultPathCStr = defaultPathString.empty() ? nullptr : defaultPathString.c_str(); SDL_ShowSaveFileDialog(callback, this, window, FILTERS[TYPE_FILTERS[type]], std::size(FILTERS[TYPE_FILTERS[type]]), - nullptr); + defaultPathCStr); this->type = type; } diff --git a/src/dialog.hpp b/src/dialog.hpp index b51a98c..8072008 100644 --- a/src/dialog.hpp +++ b/src/dialog.hpp @@ -57,6 +57,7 @@ namespace anm2ed X(FFMPEG_PATH_SET, EXECUTABLE) \ X(PNG_DIRECTORY_SET, NO_FILTER) \ X(PNG_PATH_SET, PNG) \ + X(REGION_EXPORT_PATH_SET, PNG) \ X(GIF_PATH_SET, GIF) \ X(WEBM_PATH_SET, WEBM) \ X(MP4_PATH_SET, MP4) @@ -85,7 +86,7 @@ namespace anm2ed Dialog() = default; Dialog(SDL_Window*); void file_open(Type type, bool isMany = false); - void file_save(Type type); + void file_save(Type type, const std::filesystem::path& defaultPath = {}); void folder_open(Type type); bool is_selected(Type type) const; void reset(); diff --git a/src/imgui/actions.hpp b/src/imgui/actions.hpp index fd235ae..7365f42 100644 --- a/src/imgui/actions.hpp +++ b/src/imgui/actions.hpp @@ -29,6 +29,7 @@ namespace anm2ed::imgui X(ACTION_RELOAD, BASIC_RELOAD, -1) \ X(ACTION_REPLACE, BASIC_REPLACE, -1) \ X(ACTION_SAVE, BASIC_SAVE, -1) \ + X(ACTION_EXPORT, BASIC_EXPORT, -1) \ X(ACTION_OPEN_DIRECTORY, BASIC_OPEN_DIRECTORY, -1) \ X(ACTION_SET_FILE_PATH, BASIC_SET_FILE_PATH, -1) \ X(ACTION_PACK, BASIC_PACK, -1) \ diff --git a/src/imgui/window/timeline.cpp b/src/imgui/window/timeline.cpp index f4f44a0..bca5011 100644 --- a/src/imgui/window/timeline.cpp +++ b/src/imgui/window/timeline.cpp @@ -99,6 +99,8 @@ namespace anm2ed::imgui constexpr auto FRAME_MULTIPLE = 5; constexpr auto FRAME_TOOLTIP_HOVER_DELAY = 0.75f; + constexpr auto DRAG_DROP_SOURCE_FLAGS = + ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers; #define ITEM_CHILD_WIDTH ImGui::GetTextLineHeightWithSpacing() * 12.5 @@ -1531,40 +1533,6 @@ namespace anm2ed::imgui return rows; }; - auto row_label_get = [&](const TimelineRowReference& row) -> std::string - { - if (row.isGroup) - { - TimelineItemRow groupRow{.type = row.type, .id = row.id, .index = row.index, .isGroup = true}; - auto group = row_group_get(groupRow); - if (!group || group->name.empty()) return localize.get(TEXT_NEW_GROUP); - return group->name; - } - if (row.type == LAYER) - { - auto layer = layer_get(row.id); - if (!layer) return localize.get(TYPE_STRINGS[row.type]); - return std::vformat(localize.get(FORMAT_LAYER), - std::make_format_args(layer->id, layer->name, layer->spritesheetId)); - } - if (row.type == NULL_) - { - auto null = null_get(row.id); - if (!null) return localize.get(TYPE_STRINGS[row.type]); - return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(null->id, null->name)); - } - return localize.get(TYPE_STRINGS[type_index(row.type)]); - }; - - auto row_drag_tooltip_draw = [&](const std::vector& rows) - { - for (auto row : rows) - { - auto label = row_label_get(row); - ImGui::TextUnformatted(label.c_str()); - } - }; - auto item_remove = [&]() { auto targetRows = selected_row_references_get(); @@ -2334,12 +2302,11 @@ namespace anm2ed::imgui imguiStyle.HoverDelayNormal = previousTooltipDelay; } - if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) + if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) { rowDragReferences = row_drag_references_get(row); ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), (int)rowDragReferences.size() * (int)sizeof(TimelineRowReference)); - row_drag_tooltip_draw(rowDragReferences); ImGui::EndDragDropSource(); } @@ -2523,12 +2490,11 @@ namespace anm2ed::imgui if (type == LAYER || type == NULL_) { - if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) + if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) { rowDragReferences = row_drag_references_get(row); ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), (int)rowDragReferences.size() * (int)sizeof(TimelineRowReference)); - row_drag_tooltip_draw(rowDragReferences); ImGui::EndDragDropSource(); } diff --git a/src/imgui/window/window.cpp b/src/imgui/window/window.cpp index 45c1dd7..4a987df 100644 --- a/src/imgui/window/window.cpp +++ b/src/imgui/window/window.cpp @@ -32,6 +32,23 @@ namespace anm2ed::imgui static constexpr auto PADDING_MAX = 100; static constexpr auto MERGE_APPEND_RIGHT = 0; static constexpr auto MERGE_APPEND_BOTTOM = 1; + static constexpr auto DRAG_DROP_SOURCE_FLAGS = + ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers; + + bool is_drag_drop_active() { return ImGui::GetDragDropPayload() != nullptr; } + + enum class AnimationDropZone + { + BEFORE, + INSIDE, + AFTER + }; + + enum class AnimationDragDropType + { + ANIMATION, + GROUP + }; struct SpritesheetMergeOptions { @@ -49,6 +66,31 @@ namespace anm2ed::imgui bool isDeleteAnimationsAfter{}; }; + struct AnimationDragDropItem + { + AnimationDragDropType type{AnimationDragDropType::ANIMATION}; + int id{-1}; + }; + + struct RegionExportOptions + { + int spritesheetId{-1}; + int regionId{-1}; + std::filesystem::path path{}; + bool isMakeSpritesheet{}; + bool isRemoveCurrent{}; + }; + + std::filesystem::path region_export_path_default_get(const std::filesystem::path& currentPath, + const std::string& regionName) + { + auto directory = currentPath.parent_path(); + auto filename = path::from_utf8(regionName).filename(); + if (filename.empty()) filename = "region"; + filename += ".png"; + return directory / filename; + } + int window_element_count_get(const Window& window, const Element* container) { int count{}; @@ -375,6 +417,29 @@ namespace anm2ed::imgui return (int)animations.children.size(); } + int window_animation_group_child_index_get(const Element& animations, int groupId) + { + for (int i = 0; i < (int)animations.children.size(); ++i) + if (animations.children[i].type == ElementType::GROUP && animations.children[i].id == groupId) return i; + return -1; + } + + int window_animation_group_child_insert_index_get(const Element& animations, int groupId, AnimationDropZone dropZone) + { + auto groupChildIndex = window_animation_group_child_index_get(animations, groupId); + if (groupChildIndex == -1) return (int)animations.children.size(); + if (dropZone == AnimationDropZone::BEFORE) return groupChildIndex; + if (dropZone == AnimationDropZone::AFTER) return groupChildIndex + 1; + + auto insertIndex = groupChildIndex + 1; + for (int i = 0; i < (int)animations.children.size(); ++i) + { + auto& animation = animations.children[i]; + if (animation.type == ElementType::ANIMATION && animation.groupId == groupId) insertIndex = i + 1; + } + return insertIndex; + } + int window_animation_index_from_child_index_get(const Element& animations, int childIndex) { int current{}; @@ -387,6 +452,15 @@ namespace anm2ed::imgui return -1; } + AnimationDropZone window_animation_drop_zone_get(ImVec2 min, ImVec2 max) + { + auto third = (max.y - min.y) / 3.0f; + auto mouseY = ImGui::GetIO().MousePos.y; + if (mouseY < min.y + third) return AnimationDropZone::BEFORE; + if (mouseY >= max.y - third) return AnimationDropZone::AFTER; + return AnimationDropZone::INSIDE; + } + std::set window_animation_group_ids_get(const Element& animations) { std::set result{}; @@ -395,6 +469,192 @@ namespace anm2ed::imgui return result; } + void window_animation_drag_drop_item_push(std::vector& items, AnimationDragDropItem item) + { + if (item.id < 0) return; + auto it = std::find_if(items.begin(), items.end(), [&](const AnimationDragDropItem& current) + { return current.type == item.type && current.id == item.id; }); + if (it == items.end()) items.push_back(item); + } + + bool is_window_animation_drag_drop_item_selected(Document& document, const Window& window, + AnimationDragDropItem item) + { + if (item.type == AnimationDragDropType::GROUP) return window.selection.contains(item.id); + return document.animation.selection.contains(item.id); + } + + std::vector window_animation_drag_drop_items_get(Document& document, const Window& window, + AnimationDragDropItem fallback) + { + std::vector result{}; + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + if (animations && is_window_animation_drag_drop_item_selected(document, window, fallback)) + { + auto groupIds = window_animation_group_ids_get(*animations); + for (auto groupId : window.selection) + if (groupIds.contains(groupId)) + window_animation_drag_drop_item_push(result, {AnimationDragDropType::GROUP, groupId}); + for (auto animationIndex : document.animation.selection) + if (window_animation_child_index_get(*animations, animationIndex) != -1) + window_animation_drag_drop_item_push(result, {AnimationDragDropType::ANIMATION, animationIndex}); + } + if (result.empty()) window_animation_drag_drop_item_push(result, fallback); + return result; + } + + std::vector window_animation_payload_items_get(const ImGuiPayload& payload) + { + if (payload.DataSize % (int)sizeof(AnimationDragDropItem) != 0) return {}; + auto payloadItems = static_cast(payload.Data); + auto payloadCount = payload.DataSize / sizeof(AnimationDragDropItem); + return {payloadItems, payloadItems + payloadCount}; + } + + bool is_window_animation_drag_drop_grouped(const std::vector& items) + { + return std::any_of(items.begin(), items.end(), + [](const AnimationDragDropItem& item) { return item.type == AnimationDragDropType::GROUP; }); + } + + void window_animation_items_move(Window& window, Document& document, std::vector items, + int targetChildIndex, int targetGroupId) + { + auto animations = window_container_get(window, document.anm2); + if (!animations) return; + + auto groupIds = window_animation_group_ids_get(*animations); + auto groupId = groupIds.contains(targetGroupId) ? targetGroupId : -1; + std::set draggedAnimationIds{}; + std::set draggedGroupIds{}; + for (auto item : items) + { + if (item.type == AnimationDragDropType::GROUP && groupIds.contains(item.id)) + draggedGroupIds.insert(item.id); + else if (item.type == AnimationDragDropType::ANIMATION && + window_animation_child_index_get(*animations, item.id) != -1) + draggedAnimationIds.insert(item.id); + } + if (draggedAnimationIds.empty() && draggedGroupIds.empty()) return; + + std::vector childIndices{}; + std::set directAnimationChildIndices{}; + int animationIndex{}; + for (int i = 0; i < (int)animations->children.size(); ++i) + { + auto& item = animations->children[i]; + if (item.type == ElementType::GROUP) + { + if (draggedGroupIds.contains(item.id)) childIndices.push_back(i); + continue; + } + + if (item.type != ElementType::ANIMATION) continue; + auto isGroupDragged = draggedGroupIds.contains(item.groupId); + auto isAnimationDragged = draggedAnimationIds.contains(animationIndex); + if (isGroupDragged || isAnimationDragged) + { + if (isAnimationDragged && !isGroupDragged) + { + item.groupId = groupId; + directAnimationChildIndices.insert(i); + } + childIndices.push_back(i); + } + ++animationIndex; + } + std::sort(childIndices.begin(), childIndices.end()); + childIndices.erase(std::unique(childIndices.begin(), childIndices.end()), childIndices.end()); + + auto movedChildIndices = anm2ed::util::vector::move_indices_to_position(animations->children, childIndices, + targetChildIndex); + if (movedChildIndices.empty()) return; + + document.animation.selection.clear(); + window.selection = draggedGroupIds; + auto sourceIt = childIndices.begin(); + auto movedIt = movedChildIndices.begin(); + for (; sourceIt != childIndices.end() && movedIt != movedChildIndices.end(); ++sourceIt, ++movedIt) + { + if (!directAnimationChildIndices.contains(*sourceIt)) continue; + auto movedAnimationIndex = window_animation_index_from_child_index_get(*animations, *movedIt); + if (movedAnimationIndex != -1) document.animation.selection.insert(movedAnimationIndex); + } + } + + void window_animation_move_command_push(Window& window, Manager& manager, std::vector items, + int targetGroupId, + auto target_child_index_get) + { + if (items.empty()) return; + manager.command_push({manager.selected, [&window, items, targetGroupId, target_child_index_get](Manager&, + Document& document) + mutable + { + auto move = [&]() + { + auto animations = window_container_get(window, document.anm2); + if (!animations) return; + window_animation_items_move(window, document, items, target_child_index_get(*animations), + targetGroupId); + }; + window_edit(window, document, localize.get(EDIT_MOVE_ANIMATIONS), move); + }}); + } + + void window_animation_drag_drop_source_update(Document& document, const Window& window, AnimationDragDropItem fallback) + { + if (!ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) return; + + static std::vector dragDropItems{}; + dragDropItems = window_animation_drag_drop_items_get(document, window, fallback); + ImGui::SetDragDropPayload("Animation Drag Drop", dragDropItems.data(), + dragDropItems.size() * sizeof(AnimationDragDropItem)); + ImGui::EndDragDropSource(); + } + + bool window_animation_group_drag_drop_update(Window& window, Manager& manager, int groupId, ImVec2 itemMin, + ImVec2 itemMax) + { + if (!ImGui::BeginDragDropTarget()) return false; + + bool isDelivered{}; + if (auto payload = ImGui::AcceptDragDropPayload( + "Animation Drag Drop", + ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + { + auto items = window_animation_payload_items_get(*payload); + if (items.empty()) + { + ImGui::EndDragDropTarget(); + return false; + } + + auto dropZone = window_animation_drop_zone_get(itemMin, itemMax); + auto isDropIntoGroup = dropZone == AnimationDropZone::INSIDE && !is_window_animation_drag_drop_grouped(items); + if (isDropIntoGroup) + drop_box_draw(ImGui::GetWindowDrawList(), itemMin, itemMax); + else + drop_line_draw(ImGui::GetWindowDrawList(), itemMin, itemMax, dropZone != AnimationDropZone::BEFORE); + + if (payload->IsDelivery()) + { + auto targetGroupId = isDropIntoGroup ? groupId : -1; + window_animation_move_command_push( + window, manager, items, targetGroupId, [groupId, dropZone, isDropIntoGroup](const Element& items) + { + auto targetDropZone = !isDropIntoGroup && dropZone == AnimationDropZone::INSIDE ? AnimationDropZone::AFTER + : dropZone; + return window_animation_group_child_insert_index_get(items, groupId, targetDropZone); + }); + isDelivered = true; + } + } + + ImGui::EndDragDropTarget(); + return isDelivered; + } + bool is_window_animation_grouped(const std::set& groupIds, const Element& animation) { return animation.groupId != -1 && groupIds.contains(animation.groupId); @@ -681,6 +941,152 @@ namespace anm2ed::imgui } } + bool window_region_pixels_get(const Element& region, const Texture& texture, std::vector& pixels, + ivec2& exportSize) + { + auto minPoint = ivec2(glm::min(region.crop, region.crop + region.size)); + auto maxPoint = ivec2(glm::max(region.crop, region.crop + region.size)); + exportSize = maxPoint - minPoint; + if (exportSize.x <= 0 || exportSize.y <= 0 || texture.size.x <= 0 || texture.size.y <= 0 || texture.pixels.empty()) + return false; + + auto pixelCount = (size_t)exportSize.x * (size_t)exportSize.y * texture::CHANNELS; + pixels.assign(pixelCount, 0); + + for (int y = 0; y < exportSize.y; y++) + { + auto sourceY = minPoint.y + y; + if (sourceY < 0 || sourceY >= texture.size.y) continue; + + for (int x = 0; x < exportSize.x; x++) + { + auto sourceX = minPoint.x + x; + if (sourceX < 0 || sourceX >= texture.size.x) continue; + + auto sourceIndex = ((size_t)sourceY * (size_t)texture.size.x + (size_t)sourceX) * texture::CHANNELS; + auto destinationIndex = ((size_t)y * (size_t)exportSize.x + (size_t)x) * texture::CHANNELS; + if (sourceIndex + texture::CHANNELS > texture.pixels.size() || + destinationIndex + texture::CHANNELS > pixels.size()) + continue; + std::copy_n(texture.pixels.data() + sourceIndex, texture::CHANNELS, pixels.data() + destinationIndex); + } + } + + return true; + } + + bool window_region_export(Document& document, const RegionExportOptions& options, int& exportedSpritesheetId) + { + auto pathString = path::to_utf8(options.path); + if (options.path.empty()) pathString = "in memory"; + if (options.path.empty() && !options.isMakeSpritesheet) + { + toasts.push(localize.get(TOAST_EXPORT_REGION_PATH_EMPTY)); + logger.error(localize.get(TOAST_EXPORT_REGION_PATH_EMPTY, anm2ed::ENGLISH)); + return false; + } + + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, options.spritesheetId); + auto region = spritesheet ? element_child_id_get(*spritesheet, ElementType::REGION, options.regionId) : nullptr; + auto texture = document.texture_get(options.spritesheetId); + if (!spritesheet || !region || !texture || !texture->is_valid()) + { + toasts.push(std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED), std::make_format_args("", pathString))); + logger.error(std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED, anm2ed::ENGLISH), + std::make_format_args("", pathString))); + return false; + } + + auto sourceRegion = *region; + auto regionName = sourceRegion.name; + std::vector pixels{}; + ivec2 exportSize{}; + if (!window_region_pixels_get(sourceRegion, *texture, pixels, exportSize)) + { + toasts.push(std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED), std::make_format_args(regionName, pathString))); + logger.error(std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED, anm2ed::ENGLISH), + std::make_format_args(regionName, pathString))); + return false; + } + + auto outputPath = options.path; + if (!outputPath.empty()) + { + outputPath.replace_extension(".png"); + outputPath = window_asset_path_get(document, outputPath); + pathString = path::to_utf8(outputPath); + WorkingDirectory workingDirectory(document.directory_get()); + path::ensure_directory(outputPath.parent_path()); + if (!Texture::write_pixels_png(outputPath, exportSize, pixels.data())) + { + toasts.push( + std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED), std::make_format_args(regionName, pathString))); + logger.error(std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED, anm2ed::ENGLISH), + std::make_format_args(regionName, pathString))); + return false; + } + } + + exportedSpritesheetId = -1; + if (options.isMakeSpritesheet || options.isRemoveCurrent) + { + document.anm2_textures_snapshot(localize.get(EDIT_EXPORT_REGION)); + + if (options.isMakeSpritesheet) + { + auto spritesheets = document.anm2.element_get(ElementType::SPRITESHEETS); + if (!spritesheets) return false; + + auto exported = element_make(ElementType::SPRITESHEET); + exported.id = element_child_next_id_get(*spritesheets, ElementType::SPRITESHEET); + exported.path = outputPath; + + auto exportedRegion = sourceRegion; + exportedRegion.id = element_child_next_id_get(exported, ElementType::REGION); + exportedRegion.crop = {}; + exportedRegion.size = vec2(exportSize); + if (exportedRegion.origin == Origin::TOP_LEFT) + exportedRegion.pivot = {}; + else if (exportedRegion.origin == Origin::CENTER) + exportedRegion.pivot = exportedRegion.size * 0.5f; + + exported.children.push_back(exportedRegion); + spritesheets->children.push_back(exported); + document.textures[exported.id] = Texture(pixels.data(), exportSize); + document.texturePaths[exported.id] = exported.path; + document.spritesheet.reference = exported.id; + document.spritesheet.selection = {exported.id}; + document.region.reference = exportedRegion.id; + document.region.selection = {exportedRegion.id}; + exportedSpritesheetId = exported.id; + + if (!outputPath.empty()) + document.spritesheet_hash_set_saved(exported.id); + else + document.spritesheetSaveHashes[exported.id] = 0; + } + + if (options.isRemoveCurrent) + { + if (auto sourceSpritesheet = document.anm2.element_get(ElementType::SPRITESHEET, options.spritesheetId)) + element_child_id_erase(*sourceSpritesheet, ElementType::REGION, options.regionId); + document.anm2.region_frames_sync(true); + if (!options.isMakeSpritesheet) + { + document.region.reference = -1; + document.region.selection.clear(); + } + } + + document.change(Document::SPRITESHEETS); + } + + toasts.push(std::vformat(localize.get(TOAST_EXPORT_REGION), std::make_format_args(regionName, pathString))); + logger.info( + std::vformat(localize.get(TOAST_EXPORT_REGION, anm2ed::ENGLISH), std::make_format_args(regionName, pathString))); + return true; + } + int window_footer_button_count_get(const Window& window) { int count{}; @@ -934,7 +1340,8 @@ namespace anm2ed::imgui if (isFontPushed) ImGui::PopFont(); - if (window.newElementId == key || window.scrollQueued == key || scrollTargetId == key) + if ((window.newElementId == key || window.scrollQueued == key || scrollTargetId == key) && + !is_drag_drop_active()) { ImGui::SetScrollHereY(0.5f); if (window.newElementId == key) window.newElementId = -1; @@ -1105,19 +1512,8 @@ namespace anm2ed::imgui window.row_drag_drop_update = [](Window& window, Manager& manager, Document& document, const Element&, int index) { auto& anm2 = document.anm2; - auto& selection = document.animation.selection; - if (ImGui::BeginDragDropSource()) - { - static std::vector dragDropSelection{}; - dragDropSelection.assign(selection.begin(), selection.end()); - ImGui::SetDragDropPayload("Animation Drag Drop", dragDropSelection.data(), - dragDropSelection.size() * sizeof(int)); - for (auto& dragIndex : dragDropSelection) - if (auto dragAnimation = anm2.element_get(ElementType::ANIMATION, dragIndex)) - ImGui::Text("%s", dragAnimation->name.c_str()); - ImGui::EndDragDropSource(); - } + window_animation_drag_drop_source_update(document, window, {AnimationDragDropType::ANIMATION, index}); if (ImGui::BeginDragDropTarget()) { @@ -1125,54 +1521,27 @@ namespace anm2ed::imgui "Animation Drag Drop", ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { + auto items = window_animation_payload_items_get(*payload); + if (items.empty()) + { + ImGui::EndDragDropTarget(); + return false; + } + auto itemMin = ImGui::GetItemRectMin(); auto itemMax = ImGui::GetItemRectMax(); auto isDropAfter = is_drop_after(itemMin, itemMax); drop_line_draw(ImGui::GetWindowDrawList(), itemMin, itemMax, isDropAfter); - auto payloadIndices = (int*)(payload->Data); - auto payloadCount = payload->DataSize / sizeof(int); - std::vector indices(payloadIndices, payloadIndices + payloadCount); - std::sort(indices.begin(), indices.end()); if (payload->IsDelivery()) { auto targetIndex = index + (isDropAfter ? 1 : 0); auto targetGroupId = -1; if (auto targetAnimation = anm2.element_get(ElementType::ANIMATION, index)) targetGroupId = targetAnimation->groupId; - manager.command_push({manager.selected, [&window, indices, targetIndex, targetGroupId](Manager&, Document& document) mutable - { - auto move = [&]() - { - auto items = window_container_get(window, document.anm2); - if (!items) return; - - auto groupIds = window_animation_group_ids_get(*items); - auto groupId = groupIds.contains(targetGroupId) ? targetGroupId : -1; - std::vector childIndices{}; - childIndices.reserve(indices.size()); - for (auto animationIndex : indices) - { - auto childIndex = window_animation_child_index_get(*items, animationIndex); - if (childIndex == -1) continue; - if (auto animation = vector::find(items->children, childIndex)) - animation->groupId = groupId; - childIndices.push_back(childIndex); - } - - auto targetChildIndex = window_animation_child_insert_index_get(*items, targetIndex); - auto movedChildIndices = - anm2ed::util::vector::move_indices_to_position(items->children, childIndices, - targetChildIndex); - document.animation.selection.clear(); - for (auto childIndex : movedChildIndices) - { - auto animationIndex = window_animation_index_from_child_index_get(*items, childIndex); - if (animationIndex != -1) document.animation.selection.insert(animationIndex); - } - }; - window_edit(window, document, localize.get(EDIT_MOVE_ANIMATIONS), move); - }}); + window_animation_move_command_push(window, manager, items, targetGroupId, + [targetIndex](const Element& items) + { return window_animation_child_insert_index_get(items, targetIndex); }); ImGui::EndDragDropTarget(); return true; } @@ -1305,7 +1674,8 @@ namespace anm2ed::imgui if (isFontPushed) ImGui::PopFont(); - if (window.newElementId == key || window.scrollQueued == key || scrollTargetId == key) + if ((window.newElementId == key || window.scrollQueued == key || scrollTargetId == key) && + !is_drag_drop_active()) { ImGui::SetScrollHereY(0.5f); if (window.newElementId == key) window.newElementId = -1; @@ -1386,6 +1756,8 @@ namespace anm2ed::imgui tree_node_input_text(label, std::format("###Document #{} Animation Group #{}", manager.selected, item.id), name, isGroupSelected, treeFlags, window.renameState); + auto groupItemMin = ImGui::GetItemRectMin(); + auto groupItemMax = ImGui::GetItemRectMax(); auto isGroupOpen = tree.isOpen; auto isGroupClicked = tree.isClicked; if (tree.isRenameStarted) @@ -1414,7 +1786,8 @@ namespace anm2ed::imgui window.renameId = -1; window.renameText.clear(); } - if (isGroupOpen != item.isExpanded) + if (isGroupOpen != item.isExpanded && !is_drag_drop_active() && + !ImGui::IsMouseDragging(ImGuiMouseButton_Left)) { auto targetGroupId = item.id; manager.command_push({manager.selected, [targetGroupId, isGroupOpen](Manager&, Document& document) @@ -1430,20 +1803,26 @@ namespace anm2ed::imgui }}); } if (isGroupClicked) group_selection_apply(item.id); + window_animation_drag_drop_source_update(document, window, {AnimationDragDropType::GROUP, item.id}); + if (window_animation_group_drag_drop_update(window, manager, item.id, groupItemMin, groupItemMax)) + isRowsDone = true; if (isGroupOpen) { - int groupAnimationIndex{}; - for (auto& animation : container->children) + if (!isRowsDone) { - if (animation.type != ElementType::ANIMATION) continue; - if (animation.groupId == item.id) - if (animation_row_draw(animation, groupAnimationIndex)) - { - isRowsDone = true; - break; - } - ++groupAnimationIndex; + int groupAnimationIndex{}; + for (auto& animation : container->children) + { + if (animation.type != ElementType::ANIMATION) continue; + if (animation.groupId == item.id) + if (animation_row_draw(animation, groupAnimationIndex)) + { + isRowsDone = true; + break; + } + ++groupAnimationIndex; + } } ImGui::TreePop(); } @@ -1991,6 +2370,7 @@ namespace anm2ed::imgui window.unavailableText = TEXT_SELECT_SPRITESHEET; window.editElement = element_make(ElementType::REGION); window.popup = PopupHelper(LABEL_REGION_PROPERTIES, POPUP_SMALL_NO_HEIGHT); + window.popup2 = PopupHelper(LABEL_EXPORT_REGION, POPUP_SMALL_NO_HEIGHT); window.storage_get = [](Document& document) -> Storage& { return document.region; }; window.is_available = [](Document& document) { return document.anm2.element_get(ElementType::SPRITESHEET, document.spritesheet.reference); }; @@ -2319,7 +2699,7 @@ namespace anm2ed::imgui } ImGui::PopStyleVar(2); - if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip)) + if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) { isRegionDragDropSourceSubmitted = true; if (selection.contains(id)) @@ -2406,7 +2786,7 @@ namespace anm2ed::imgui ImGui::EndChild(); - if (isNewRegion) + if (isNewRegion && !is_drag_drop_active()) { ImGui::SetScrollHereY(0.5f); window.newElementId = -1; @@ -2419,7 +2799,7 @@ namespace anm2ed::imgui auto regionDragPayload = isRegionMoved ? nullptr : ImGui::GetDragDropPayload(); bool isRegionDragActive = regionDragPayload && regionDragPayload->IsDataType("Region Drag Drop"); if (isRegionDragActive && !isRegionDragDropSourceSubmitted && !window.dragSelection.empty() && - ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceExtern | ImGuiDragDropFlags_SourceNoPreviewTooltip)) + ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceExtern | DRAG_DROP_SOURCE_FLAGS)) { ImGui::SetDragDropPayload("Region Drag Drop", window.dragSelection.data(), window.dragSelection.size() * sizeof(int)); @@ -2494,6 +2874,12 @@ namespace anm2ed::imgui actions.add(ACTION_TRIM, [&]() { return !selection.empty() && (bool)window.trim; }, [&]() { window_command_run(window, manager, settings, document, clipboard, window.trim); }, TOOLTIP_TRIM_REGIONS); + actions.add(ACTION_EXPORT, [&]() { return selection.size() == 1; }, + [&]() + { + window.editId = *selection.begin(); + window.popup2.open(); + }); actions.separator(); actions.add(ACTION_COPY, [&]() { return !selection.empty() && (bool)window.copy; }, [&]() { window_command_run(window, manager, settings, document, clipboard, window.copy); }); @@ -2505,7 +2891,7 @@ namespace anm2ed::imgui window.footer_update = [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard& clipboard, Document& document) { - auto rowOneWidgetSize = widget_size_with_row_get(2); + auto rowOneWidgetSize = widget_size_with_row_get(3); shortcut(manager.chords[SHORTCUT_ADD]); if (ImGui::Button(localize.get(BASIC_ADD), rowOneWidgetSize) && window.add) @@ -2514,12 +2900,23 @@ namespace anm2ed::imgui ImGui::SameLine(); + ImGui::BeginDisabled(document.region.selection.size() != 1); + if (ImGui::Button(localize.get(BASIC_EXPORT), rowOneWidgetSize) && document.region.selection.size() == 1) + { + window.editId = *document.region.selection.begin(); + window.popup2.open(); + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + shortcut(manager.chords[SHORTCUT_REMOVE]); if (ImGui::Button(localize.get(BASIC_REMOVE_UNUSED), rowOneWidgetSize) && window.remove) window_command_run(window, manager, settings, document, clipboard, window.remove); set_item_tooltip_shortcut(localize.get(TOOLTIP_REMOVE_UNUSED_REGIONS), settings.shortcutAdd); }; - window.popup_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) + window.popup_update = [](Window& window, Manager& manager, Settings& settings, Resources& resources, Clipboard&, + Document& document) { auto& anm2 = document.anm2; auto& spritesheetReference = document.spritesheet.reference; @@ -2658,6 +3055,88 @@ namespace anm2ed::imgui } window.popup.end(); + + window.popup2.trigger(); + if (ImGui::BeginPopupModal(window.popup2.label(), &window.popup2.isOpen, ImGuiWindowFlags_NoResize)) + { + auto close = [&]() + { + window.editId = -1; + window.popup2.close(); + }; + + auto exportRegionId = window.editId != -1 ? window.editId : reference; + auto targetRegion = exportRegionId == -1 ? nullptr : region_get(exportRegionId); + auto texture = document.texture_get(spritesheetReference); + auto isTextureValid = texture && texture->is_valid() && !texture->pixels.empty(); + auto isTargetValid = targetRegion && isTextureValid; + + if (!targetRegion) + { + close(); + ImGui::EndPopup(); + window.popup2.end(); + return; + } + + if (window.popup2.isJustOpened) + settings.exportRegionPath = region_export_path_default_get(settings.exportRegionPath, targetRegion->name); + + if (window.dialog && window.dialog->is_selected(Dialog::REGION_EXPORT_PATH_SET)) + { + settings.exportRegionPath = window.dialog->path; + window.dialog->reset(); + } + + auto childSize = child_size_get(5); + if (ImGui::BeginChild("##Export Region Child", childSize, ImGuiChildFlags_Borders)) + { + if (ImGui::ImageButton("##Export Region Path Set", resources.icons[icon::FOLDER].id, icon_size_get()) && + window.dialog) + window.dialog->file_save(Dialog::REGION_EXPORT_PATH_SET, settings.exportRegionPath); + ImGui::SameLine(); + input_text_path(localize.get(LABEL_OUTPUT_PATH), &settings.exportRegionPath); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OUTPUT_PATH)); + + ImGui::Checkbox(localize.get(LABEL_EXPORT_MAKE_SPRITESHEET), &settings.isExportRegionMakeSpritesheet); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EXPORT_MAKE_SPRITESHEET)); + + ImGui::Checkbox(localize.get(LABEL_EXPORT_REMOVE_CURRENT_REGION), &settings.isExportRegionRemoveCurrent); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EXPORT_REMOVE_CURRENT_REGION)); + } + ImGui::EndChild(); + + auto widgetSize = widget_size_with_row_get(2); + auto isTargetSelected = settings.isExportRegionMakeSpritesheet || !settings.exportRegionPath.empty(); + ImGui::BeginDisabled(!isTargetValid || !isTargetSelected); + shortcut(manager.chords[SHORTCUT_CONFIRM]); + if (ImGui::Button(localize.get(BASIC_CONFIRM), widgetSize)) + { + if (!settings.exportRegionPath.empty()) settings.exportRegionPath.replace_extension(".png"); + RegionExportOptions options{.spritesheetId = spritesheetReference, + .regionId = exportRegionId, + .path = settings.exportRegionPath, + .isMakeSpritesheet = settings.isExportRegionMakeSpritesheet, + .isRemoveCurrent = settings.isExportRegionRemoveCurrent}; + manager.command_push({manager.selected, [&window, options](Manager&, Document& document) mutable + { + int exportedSpritesheetId{-1}; + if (window_region_export(document, options, exportedSpritesheetId) && + exportedSpritesheetId != -1) + window.newElementId = document.region.reference; + }}); + close(); + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) close(); + + ImGui::EndPopup(); + } + window.popup2.end(); }; return window; } @@ -2990,7 +3469,7 @@ namespace anm2ed::imgui ImGui::EndChild(); - if (isNewSpritesheet) + if (isNewSpritesheet && !is_drag_drop_active()) { ImGui::SetScrollHereY(0.5f); window.newElementId = -1; @@ -3597,7 +4076,7 @@ namespace anm2ed::imgui ImGui::EndChild(); - if (isNewSound) + if (isNewSound && !is_drag_drop_active()) { ImGui::SetScrollHereY(0.5f); window.newElementId = -1; diff --git a/src/log.cpp b/src/log.cpp index 42d916f..12fff4a 100644 --- a/src/log.cpp +++ b/src/log.cpp @@ -1,11 +1,15 @@ #include "log.hpp" +#include #include #include +#include #include #include +#include #include "file.hpp" +#include "path.hpp" #include "sdl.hpp" #include "strings.hpp" #include "time.hpp" @@ -13,6 +17,7 @@ #if _WIN32 #include #include + #include #else #include #endif @@ -21,6 +26,108 @@ using namespace anm2ed::util; namespace anm2ed { + namespace log + { + constexpr auto SESSION_LIMIT = 10; + constexpr std::uintmax_t DIRECTORY_SIZE_LIMIT = 100ull * 1024ull * 1024ull; + constexpr std::uintmax_t SESSION_SIZE_LIMIT = 25ull * 1024ull * 1024ull; + + struct SessionFile + { + std::filesystem::path path{}; + std::filesystem::file_time_type time{}; + std::uintmax_t size{}; + }; + + std::uint32_t process_id_get() + { +#if _WIN32 + return (std::uint32_t)_getpid(); +#else + return (std::uint32_t)getpid(); +#endif + } + + std::filesystem::path directory_path_get() { return sdl::preferences_directory_get() / "logs"; } + + std::filesystem::path session_path_get() + { + auto name = std::format("anm2ed_{}_{}.log", time::get("%Y-%m-%d_%H-%M-%S"), process_id_get()); + return directory_path_get() / path::from_utf8(name); + } + + std::vector session_files_get(const std::filesystem::path& directory, + const std::filesystem::path& currentPath) + { + std::vector files{}; + std::error_code ec{}; + if (!std::filesystem::is_directory(directory, ec)) return files; + + for (std::filesystem::directory_iterator it(directory, ec), end{}; !ec && it != end; it.increment(ec)) + { + auto path = it->path(); + if (path == currentPath || path.extension() != ".log") continue; + std::error_code fileEc{}; + if (!std::filesystem::is_regular_file(path, fileEc)) continue; + + auto size = std::filesystem::file_size(path, fileEc); + if (fileEc) continue; + + auto time = std::filesystem::last_write_time(path, fileEc); + if (fileEc) + { + time = std::filesystem::file_time_type::min(); + } + + files.push_back({path, time, size}); + } + + return files; + } + + void session_file_remove(const SessionFile& file, std::uintmax_t& totalSize) + { + std::error_code ec{}; + std::filesystem::remove(file.path, ec); + if (!ec && totalSize >= file.size) totalSize -= file.size; + } + + void sessions_prune(const std::filesystem::path& directory, const std::filesystem::path& currentPath) + { + auto files = session_files_get(directory, currentPath); + std::sort(files.begin(), files.end(), [](const SessionFile& left, const SessionFile& right) + { return left.time > right.time; }); + + std::uintmax_t totalSize{}; + for (const auto& file : files) + totalSize += file.size; + + while (files.size() >= SESSION_LIMIT) + { + session_file_remove(files.back(), totalSize); + files.pop_back(); + } + + while (totalSize > DIRECTORY_SIZE_LIMIT && !files.empty()) + { + session_file_remove(files.back(), totalSize); + files.pop_back(); + } + } + + void legacy_log_remove(const std::filesystem::path& currentPath) + { + auto directory = sdl::preferences_directory_get(); + if (directory.empty()) return; + + auto legacyPath = directory / "log.txt"; + if (legacyPath == currentPath) return; + + std::error_code ec{}; + std::filesystem::remove(legacyPath, ec); + } + } + void Logger::write_raw(const std::string& message) { std::lock_guard lock(mutex); @@ -35,7 +142,21 @@ namespace anm2ed { try { - file::write_string(logPath, message + '\n', "ab"); + auto lineSize = (std::uintmax_t)message.size() + 1; + auto isLineWithinLimit = logSize <= log::SESSION_SIZE_LIMIT && lineSize <= log::SESSION_SIZE_LIMIT - logSize; + if (isLineWithinLimit) + { + auto line = message + '\n'; + if (file::write_string(logPath, line, "ab")) logSize += line.size(); + } + else if (!isLogLimitReached) + { + std::string line = + "[WARNING] Session log size limit reached; suppressing further file logs for this session.\n"; + if (logSize + line.size() <= log::SESSION_SIZE_LIMIT) + if (file::write_string(logPath, line, "ab")) logSize += line.size(); + isLogLimitReached = true; + } } catch (...) { @@ -151,10 +272,27 @@ namespace anm2ed void Logger::open(const std::filesystem::path& path) { logPath = path; + logSize = 0; + isLogLimitReached = false; + if (!logPath.empty()) + { + std::error_code ec{}; + auto directory = logPath.parent_path(); + if (!directory.empty()) std::filesystem::create_directories(directory, ec); + log::legacy_log_remove(logPath); + log::sessions_prune(directory, logPath); + logSize = std::filesystem::file_size(logPath, ec); + if (ec) logSize = 0; + isLogLimitReached = logSize >= log::SESSION_SIZE_LIMIT; + } stderr_redirect_start(); } - std::filesystem::path Logger::path() { return sdl::preferences_directory_get() / "log.txt"; } + std::filesystem::path Logger::path() + { + static auto path = log::session_path_get(); + return path; + } Logger::Logger() { diff --git a/src/log.hpp b/src/log.hpp index 483a9b5..273eb93 100644 --- a/src/log.hpp +++ b/src/log.hpp @@ -1,10 +1,11 @@ #pragma once +#include #include #include +#include #include #include -#include #include namespace anm2ed @@ -46,9 +47,11 @@ namespace anm2ed class Logger { std::filesystem::path logPath{}; + std::uintmax_t logSize{}; std::mutex mutex{}; std::thread stderrThread{}; bool isStderrRedirecting{}; + bool isLogLimitReached{}; int stderrPipeReadFd{-1}; int stderrPipeWriteFd{-1}; int stderrOriginalFd{-1}; diff --git a/src/main.cpp b/src/main.cpp index 0bd67b9..863d750 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,33 +5,93 @@ #ifdef _WIN32 #define SDL_MAIN_HANDLED #include + #include + #include #include #include + #include #endif +#ifdef _WIN32 +namespace anm2ed::main +{ + struct CommandLineArguments + { + std::vector strings{}; + std::vector pointers{}; + }; + + std::string wstring_utf8_get(std::wstring_view value) + { + if (value.empty()) return {}; + auto size = WideCharToMultiByte(CP_UTF8, 0, value.data(), (int)value.size(), nullptr, 0, nullptr, nullptr); + if (size <= 0) return {}; + + std::string utf8((std::size_t)size, '\0'); + WideCharToMultiByte(CP_UTF8, 0, value.data(), (int)value.size(), utf8.data(), size, nullptr, nullptr); + return utf8; + } + + CommandLineArguments command_line_arguments_get() + { + int count{}; + auto wideArguments = CommandLineToArgvW(GetCommandLineW(), &count); + if (!wideArguments) return {}; + if (count <= 0) + { + LocalFree(wideArguments); + return {}; + } + + CommandLineArguments arguments{}; + arguments.strings.reserve((std::size_t)count); + for (int i = 0; i < count; ++i) + arguments.strings.push_back(wstring_utf8_get(wideArguments[i])); + LocalFree(wideArguments); + + arguments.pointers.reserve(arguments.strings.size()); + for (auto& argument : arguments.strings) + arguments.pointers.push_back(argument.c_str()); + + return arguments; + } +} +#endif + +namespace anm2ed +{ + int application_run(int argc, const char** argv) + { + return log_exceptions([&]() + { + Loader loader(argc, argv); + + if (loader.isError) return EXIT_FAILURE; + + State state(loader.window, loader.settings, loader.arguments); + + while (!state.isQuit) + state.loop(loader.window, loader.settings); + + return EXIT_SUCCESS; + }); + } +} + int main(int argc, const char** argv) { - return anm2ed::log_exceptions([&]() - { - anm2ed::Loader loader(argc, argv); - - if (loader.isError) return EXIT_FAILURE; - - anm2ed::State state(loader.window, loader.settings, loader.arguments); - - while (!state.isQuit) - state.loop(loader.window, loader.settings); - - return EXIT_SUCCESS; - }); +#ifdef _WIN32 + auto arguments = anm2ed::main::command_line_arguments_get(); + if (!arguments.pointers.empty()) + return anm2ed::application_run((int)arguments.pointers.size(), arguments.pointers.data()); +#endif + return anm2ed::application_run(argc, argv); } #ifdef _WIN32 int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { - std::vector args(__argc); - for (int i = 0; i < __argc; ++i) - args[i] = __argv[i]; - return main(__argc, args.data()); + auto arguments = anm2ed::main::command_line_arguments_get(); + return anm2ed::application_run((int)arguments.pointers.size(), arguments.pointers.data()); } #endif diff --git a/src/render.cpp b/src/render.cpp index 7cfb55f..e323531 100644 --- a/src/render.cpp +++ b/src/render.cpp @@ -4,11 +4,12 @@ #include #include #include -#include #include +#include #include +#include "file.hpp" #include "log.hpp" #include "path.hpp" #include "process.hpp" @@ -61,15 +62,10 @@ namespace anm2ed auto tempFilenameUtf8 = std::format("anm2ed_audio_{}_{}.f32", std::hash{}(pathString), SDL_GetTicks()); audioPath = temporaryDirectory / path::from_utf8(tempFilenameUtf8); - std::ofstream audioFile(audioPath, std::ios::binary); - - if (audioFile) + auto data = (const char*)audioStream.stream.data(); + auto byteCount = audioStream.stream.size() * sizeof(float); + if (file::write_string(audioPath, std::string_view(data, byteCount), "wb")) { - auto data = (const char*)audioStream.stream.data(); - auto byteCount = audioStream.stream.size() * sizeof(float); - audioFile.write(data, byteCount); - audioFile.close(); - auto sampleRate = std::max(audioStream.spec.freq, 1); auto channels = std::max(audioStream.spec.channels, 1); auto audioDurationFilter = std::string{}; diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index 18ffced..dc9ce50 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -56,6 +56,7 @@ namespace anm2ed X(BASIC_EASE_OUT, "Ease Out", "Desaceleración de Salida", "Плавный выход", "缓出", "천천히 끝남") \ X(BASIC_EASE_IN_OUT, "Ease In Out", "Aceleración y Desaceleración", "Плавный вход/выход", "缓入缓出", "천천히 시작/끝") \ X(BASIC_EVENT, "Event", "Evento", "Событие", "事件", "이벤트") \ + X(BASIC_EXPORT, "Export", "Export", "Export", "Export", "Export") \ X(BASIC_FRAME, "Frame", "Frame", "Кадр", "帧", "프레임") \ X(BASIC_FRAMES, "Frames", "Frames", "Кадры", "帧", "프레임") \ X(BASIC_GROUP, "Group", "Grupo", "Группа", "组", "그룹") \ @@ -145,6 +146,7 @@ namespace anm2ed X(EDIT_FRAME_SIZE, "Frame Size", "Tamaño de Frame", "Размер кадра", "帧大小", "프레임 크기") \ X(EDIT_FRAME_TINT, "Frame Tint", "Matiz de Frame", "Оттенок кадра", "帧色调", "프레임 색조") \ X(EDIT_FRAME_VISIBILITY, "Frame Visibility", "Visibilidad de Frame", "Видимость кадра", "帧可见", "프레임 표시") \ + X(EDIT_EXPORT_REGION, "Export Region", "Export Region", "Export Region", "Export Region", "Export Region") \ X(EDIT_GENERATE_ANIMATION_FROM_GRID, "Generate Animation from Grid", "Generar Animacion Desde Cuadricula", "Создать анимацию с сетки", "从网格转换为动画", "격자로 애니메이션 생성") \ X(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, "Generate Regions from Animations", "Generar regiones desde animaciones", "Создать регионы из анимаций", "从动画生成区域", "애니메이션에서 영역 생성") \ X(EDIT_INSERT_FRAME, "Insert Frame", "Insertar Frame", "Вставить кадр", "插入帧", "프레임 삽입하기") \ @@ -327,6 +329,9 @@ namespace anm2ed X(LABEL_MANAGER_ANM2_DRAG_DROP, "Anm2 Drag Drop", "Arrastrar y Soltar Anm2", "Anm2 Drag Drop", "Anm2 拖放", "Anm2 드래그 앤 드롭") \ X(LABEL_GROUP_PROPERTIES, "Group Properties", "Propiedades de grupo", "Свойства группы", "组属性", "그룹 속성") \ X(LABEL_REGION_PROPERTIES, "Region Properties", "Propiedades de región", "Свойства региона", "区域属性", "영역 속성") \ + X(LABEL_EXPORT_REGION, "Export Region", "Export Region", "Export Region", "Export Region", "Export Region") \ + X(LABEL_EXPORT_MAKE_SPRITESHEET, "Make Spritesheet", "Make Spritesheet", "Make Spritesheet", "Make Spritesheet", "Make Spritesheet") \ + X(LABEL_EXPORT_REMOVE_CURRENT_REGION, "Remove Region from Current Spritesheet", "Remove Region from Current Spritesheet", "Remove Region from Current Spritesheet", "Remove Region from Current Spritesheet", "Remove Region from Current Spritesheet") \ X(LABEL_REGION_PROPERTIES_ORIGIN, "Origin", "Origen", "Точка отсчета", "原点", "원점") \ X(LABEL_REGION_ORIGIN_TOP_LEFT, "Top Left", "Superior izquierda", "Верхний левый", "左上", "왼쪽 위") \ X(LABEL_REGION_ORIGIN_CENTER, "Center", "Centro", "Центр", "中心", "중앙") \ @@ -510,6 +515,9 @@ namespace anm2ed X(TOAST_DESERIALIZE_REGIONS_FAILED, "Failed to deserialize region(s): {0}", "Falla al deserializar región(es): {0}", "Не удалось десериализировать регионы: {0}", "反序列化区域失败: {0}", "영역 역직렬화 실패: {0}") \ X(TOAST_DESERIALIZE_NULLS_FAILED, "Failed to deserialize null(s): {0}", "Falla al deserializar null(s): {0}", "Не удалось десериализировать нули: {0}", "反序列化Null失败: {0}", "Null 역직렬화 실패: {0}") \ X(TOAST_DESERIALIZE_SPRITESHEETS_FAILED, "Failed to deserialize spritesheet(s): {0}", "Falla al deserializar spritesheet(s): {0}", "Не удалось десериализировать спрайт-листы: {0}", "反序列化图集失败: {0}", "스프라이트 시트 역직렬화 실패: {0}") \ + X(TOAST_EXPORT_REGION, "Saved region {0} to spritesheet: {1}", "Saved region {0} to spritesheet: {1}", "Saved region {0} to spritesheet: {1}", "Saved region {0} to spritesheet: {1}", "Saved region {0} to spritesheet: {1}") \ + X(TOAST_EXPORT_REGION_FAILED, "Could not export region {0} to: {1}", "Could not export region {0} to: {1}", "Could not export region {0} to: {1}", "Could not export region {0} to: {1}", "Could not export region {0} to: {1}") \ + X(TOAST_EXPORT_REGION_PATH_EMPTY, "Region export needs a path or an in-memory spritesheet.", "Region export needs a path or an in-memory spritesheet.", "Region export needs a path or an in-memory spritesheet.", "Region export needs a path or an in-memory spritesheet.", "Region export needs a path or an in-memory spritesheet.") \ X(TOAST_EXPORT_RENDERED_ANIMATION, "Exported rendered animation to: {0}", "Se ha exportado la animacion renderizada a: {0}", "Рендерированные анимации экспортированы в: {0}", "渲染动画导出至: {0}", "{0}에 렌더링 된 애니메이션을 내보내기 했습니다.") \ X(TOAST_EXPORT_RENDERED_ANIMATION_FAILED, "Could not output rendered animation: {0}", "No se pudo emitir la animacion renderizada: {0}", "Не удалось вывести рендерированную анимацию: {0}", "无法输出渲染动画: {0}", "{0}에 렌더링 된 애니메이션을 내보내기 할 수 없습니다.") \ X(TOAST_EXPORT_RENDERED_FRAMES, "Exported rendered frames to: {0}", "Se ha exportado los Frames renderizados a: {0}", "Рендерированные кадры экспортированы в: {0}", "渲染帧导出至: {0}", "{0}에 렌더링 된 프레임을 내보내기 했습니다.") \ @@ -674,6 +682,8 @@ namespace anm2ed X(TOOLTIP_REMOVE_ANIMATION, "Remove the selected animation(s).", "Remueve la(s) animacion(es) seleccionada(s).", "Удалить выбранные анимации.", "去除所选动画.", "선택한 애니메이션을 제거합니다.") \ X(TOOLTIP_REMOVE_ITEMS, "Remove the selected item(s).", "Remueve el/los item(s) seleccionado(s).", "Удалить выбранные предметы.", "去除所选物品.", "선택한 항목을 제거합니다.") \ X(TOOLTIP_REMOVE_UNUSED_REGIONS, "Remove unused regions (i.e., ones not used by any frame in any animation.)", "Remueve regiones no utilizadas (es decir, aquellas no usadas por ningun frame en ninguna animacion.)", "Удалить неиспользуемые регионы (т. е. те, которые не используются ни одним кадром ни в одной анимации.)", "移除未使用的区域(即未被任何动画中的任何帧使用的区域。)", "사용되지 않는 영역(어떤 애니메이션의 어떤 프레임에서도 사용되지 않는 것)를 제거합니다.") \ + X(TOOLTIP_EXPORT_MAKE_SPRITESHEET, "Make a new spritesheet from this region.", "Make a new spritesheet from this region.", "Make a new spritesheet from this region.", "Make a new spritesheet from this region.", "Make a new spritesheet from this region.") \ + X(TOOLTIP_EXPORT_REMOVE_CURRENT_REGION, "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.") \ X(TOOLTIP_TRIM_REGIONS, "Trim region to non-transparent content.", "Recorta la región al contenido no transparente.", "Обрезать регион до непрозрачного содержимого.", "将区域裁剪到非透明内容。", "영역을 불투명 콘텐츠에 맞게 자릅니다.") \ X(TOOLTIP_REMOVE_UNUSED_EVENTS, "Remove unused events (i.e., ones not used by any trigger in any animation.)", "Remueve eventos no utilizados (i. e., aquellos no usados por algun trigger en ninguna animacion.)", "Удалить неиспользуемые события (т. е. события, которые не использует ни один триггер в ни одной анимации.)", "去除未使用的事件 (未被任何动画触发的事件.)", "사용되지 않는 이벤트(어떤 애니메이션의 트리거에서도 사용되지 않는 것)를 제거합니다.") \ X(TOOLTIP_REMOVE_UNUSED_LAYERS, "Remove unused layers (i.e., ones not used in any animation.)", "Remueve capas no utilizadas (i. e., aquellos no usados en ninguna animacion.)", "Удалить неиспользуемые слои (т. е. слои, которые не используются ни одной анимацией.)", "去除未使用的动画层 (未被任何动画使用的那些)", "사용되지 않는 레이어(어떤 애니메이션에서도 사용되지 않는 것)를 제거합니다.") \ diff --git a/src/settings.cpp b/src/settings.cpp index d07ba80..4cf80ee 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1,8 +1,8 @@ #include "settings.hpp" -#include #include +#include "file.hpp" #include "log.hpp" #include "path.hpp" @@ -170,12 +170,13 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 isDefault = true; } - std::ifstream file(path); - if (!file.is_open()) + std::string fileData{}; + if (!file::read_to_string(path, &fileData, "rb")) { logger.error(std::format("Failed to open settings file: {}", pathUtf8)); return; } + std::istringstream file(fileData); std::string line{}; @@ -313,7 +314,6 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 #undef X } - file.close(); } Options Settings::anm2_options_get() const @@ -324,13 +324,14 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 std::string Settings::imgui_data_load(const std::filesystem::path& path) { auto pathUtf8 = path::to_utf8(path); - std::ifstream file(path, std::ios::in | std::ios::binary); - if (!file.is_open()) + std::string fileData{}; + if (!file::read_to_string(path, &fileData, "rb")) { logger.error( std::format("Failed to open settings file for Dear ImGui data: {}; using Dear ImGui defaults", pathUtf8)); return {}; } + std::istringstream file(fileData); std::string line{}; std::ostringstream dataStream; @@ -370,12 +371,7 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 { auto pathUtf8 = path::to_utf8(path); logger.info(std::format("Saving settings to: {}", pathUtf8)); - std::ofstream file(path, std::ios::out | std::ios::binary); - if (!file.is_open()) - { - logger.error(std::format("Failed to save settings file: {}", pathUtf8)); - return; - } + std::ostringstream file{}; file << "[Settings]\n"; @@ -432,13 +428,16 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 << "\n# Dear ImGui\n" << imguiData; - file.flush(); if (file.fail()) { logger.error(std::format("Failed while writing settings file: {}", pathUtf8)); return; } - file.close(); + if (!file::write_string(path, file.str(), "wb")) + { + logger.error(std::format("Failed to save settings file: {}", pathUtf8)); + return; + } logger.info(std::format("Saved settings to: {}", pathUtf8)); } } diff --git a/src/settings.hpp b/src/settings.hpp index 9982bb5..a5d35f6 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -169,6 +169,9 @@ namespace anm2ed X(MERGE_SPRITESHEETS_IS_MAKE_PRIMARY_REGION, mergeSpritesheetsIsMakePrimaryRegion, STRING_UNDEFINED, BOOL, true) \ X(MERGE_SPRITESHEETS_REGION_ORIGIN, mergeSpritesheetsRegionOrigin, STRING_UNDEFINED, INT, origin::TOP_LEFT) \ X(PACK_PADDING, packPadding, STRING_UNDEFINED, INT, 1) \ + X(EXPORT_REGION_PATH, exportRegionPath, STRING_UNDEFINED, PATH, "./region.png") \ + X(EXPORT_REGION_IS_MAKE_SPRITESHEET, isExportRegionMakeSpritesheet, STRING_UNDEFINED, BOOL, true) \ + X(EXPORT_REGION_IS_REMOVE_CURRENT, isExportRegionRemoveCurrent, STRING_UNDEFINED, BOOL, true) \ \ X(BAKE_INTERVAL, bakeInterval, STRING_UNDEFINED, INT, 1) \ X(BAKE_IS_ROUND_SCALE, bakeIsRoundScale, STRING_UNDEFINED, BOOL, true) \