From d926fc667771eef5c1d7731cc429d76e70f7bec5 Mon Sep 17 00:00:00 2001 From: shweet Date: Sat, 3 Oct 2026 13:27:34 -0400 Subject: [PATCH] Split window.cpp per window and drive menus from one flag table - WINDOW_FLAGS table builds every context menu, footer and shortcut set - Shared list-row and card-row renderers replace per-window copies - Layers/nulls/events share one properties popup; Manager keeps one item popup API - Regions, spritesheets and sounds drop hand-built menus, footers and shortcut blocks - Animation remove and cut share one erase path that also clears group ids - Index-mapped multi-select fixes shift-range over non-contiguous ids - Fix Remove Unused tooltip showing the Add shortcut and the missing break in item properties Co-Authored-By: Claude Opus 5.5 --- src/anm2/anm2.hpp | 3 + src/anm2/internal.hpp | 3 - src/imgui/window/animations.cpp | 954 +++++ src/imgui/window/items.cpp | 159 + src/imgui/window/regions.cpp | 546 +++ src/imgui/window/sounds.cpp | 131 + src/imgui/window/spritesheets.cpp | 368 ++ src/imgui/window/timeline/commands.cpp | 11 +- src/imgui/window/window.cpp | 4877 +++--------------------- src/imgui/window/window.hpp | 141 +- src/manager.cpp | 60 +- src/manager.hpp | 18 +- src/util/vector.hpp | 6 +- 13 files changed, 2811 insertions(+), 4466 deletions(-) create mode 100644 src/imgui/window/animations.cpp create mode 100644 src/imgui/window/items.cpp create mode 100644 src/imgui/window/regions.cpp create mode 100644 src/imgui/window/sounds.cpp create mode 100644 src/imgui/window/spritesheets.cpp diff --git a/src/anm2/anm2.hpp b/src/anm2/anm2.hpp index 41d526c..d804453 100644 --- a/src/anm2/anm2.hpp +++ b/src/anm2/anm2.hpp @@ -509,6 +509,9 @@ namespace anm2ed bool element_child_id_erase(Element&, ElementType, int); int track_frames_count_get(const Element&); int animations_count_get(const Element&); + int animations_child_index_get(const Element&, int); + int animations_child_insert_index_get(const Element&, int); + Element root_animation_make(); float interpolation_factor(Interpolation, float); void frame_mix(Element&, const Element&, float); Element frame_generate(const Element&, float); diff --git a/src/anm2/internal.hpp b/src/anm2/internal.hpp index 6db7868..f4fa3bb 100644 --- a/src/anm2/internal.hpp +++ b/src/anm2/internal.hpp @@ -61,9 +61,6 @@ namespace anm2ed ElementType group_child_type_get(ElementType); Element* content_container_get(Element&, ElementType); std::unordered_map child_ids_compact(Element&, ElementType); - int animations_child_index_get(const Element&, int); - int animations_child_insert_index_get(const Element&, int); - Element root_animation_make(); void group_frames_bake(Element&); void group_frames_restore(Element&); void group_metadata_embed(Element&); diff --git a/src/imgui/window/animations.cpp b/src/imgui/window/animations.cpp new file mode 100644 index 0000000..12733fc --- /dev/null +++ b/src/imgui/window/animations.cpp @@ -0,0 +1,954 @@ +#include "window.hpp" + +#include +#include +#include + +#include "toast.hpp" +#include "util/imgui/draw.hpp" +#include "util/imgui/layout.hpp" +#include "util/imgui/shortcut.hpp" +#include "util/imgui/tree.hpp" +#include "vector.hpp" + +using namespace anm2ed::resource; +using namespace anm2ed::types; +using namespace anm2ed::util; + +namespace anm2ed::imgui +{ + constexpr const char* ANIMATION_DRAG_DROP = "Animation Drag Drop"; + constexpr float DROP_ZONE_FRACTION = 1.0f / 3.0f; + constexpr int MERGE_OPTIONS_ROWS = 2; + constexpr float MERGE_OPTIONS_HALF = 0.5f; + constexpr int MERGE_POPUP_CHILD_COUNT = 3; + + enum class AnimationDropZone + { + BEFORE, + INSIDE, + AFTER + }; + + enum class AnimationDragDropType + { + ANIMATION, + GROUP + }; + + struct AnimationDragDropItem + { + AnimationDragDropType type{AnimationDragDropType::ANIMATION}; + int id{-1}; + + bool operator==(const AnimationDragDropItem&) const = default; + }; + + struct AnimationMergeOptions + { + std::set selection{}; + int reference{-1}; + merge::Type type{}; + bool isDeleteAnimationsAfter{}; + }; + + std::set animation_group_ids_get(const Element& animations) + { + std::set result{}; + for (const auto& item : animations.children) + if (item.type == ElementType::GROUP) result.insert(item.id); + return result; + } + + std::set animation_group_indices_get(const Element& animations, int groupId) + { + std::set result{}; + int animationIndex{}; + for (const auto& animation : animations.children) + if (animation.type == ElementType::ANIMATION) + { + if (animation.groupId == groupId) result.insert(animationIndex); + ++animationIndex; + } + return result; + } + + int animation_index_from_child_index_get(const Element& animations, int childIndex) + { + int current{}; + for (int i = 0; i < (int)animations.children.size(); ++i) + if (animations.children[i].type == ElementType::ANIMATION) + { + if (i == childIndex) return current; + ++current; + } + return -1; + } + + int animation_group_child_insert_index_get(const Element& animations, int groupId, AnimationDropZone dropZone) + { + auto group = std::ranges::find_if(animations.children, [&](const Element& item) + { return item.type == ElementType::GROUP && item.id == groupId; }); + if (group == animations.children.end()) return (int)animations.children.size(); + auto groupChildIndex = (int)(group - animations.children.begin()); + if (dropZone != AnimationDropZone::INSIDE) return groupChildIndex + (dropZone == AnimationDropZone::AFTER); + + auto insertIndex = groupChildIndex + 1; + for (int i = 0; i < (int)animations.children.size(); ++i) + if (animations.children[i].type == ElementType::ANIMATION && animations.children[i].groupId == groupId) + insertIndex = i + 1; + return insertIndex; + } + + bool is_animation_grouped(const std::set& groupIds, const Element& animation) + { + return animation.groupId != -1 && groupIds.contains(animation.groupId); + } + + std::set animation_selected_indices_get(Document& document, const Window& window) + { + std::set result(document.animation.selection.begin(), document.animation.selection.end()); + if (auto animations = document.anm2.element_get(ElementType::ANIMATIONS)) + for (auto groupId : window.selection) + result.merge(animation_group_indices_get(*animations, groupId)); + return result; + } + + std::vector animation_groupable_indices_get(Document& document) + { + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + auto& selection = document.animation.selection; + if (!animations || selection.empty()) return {}; + + auto groupIds = animation_group_ids_get(*animations); + std::vector result{}; + int index{}; + for (const auto& animation : animations->children) + if (animation.type == ElementType::ANIMATION) + { + if (selection.contains(index) && is_animation_grouped(groupIds, animation)) return {}; + if (selection.contains(index)) result.push_back(index); + ++index; + } + return result.size() == selection.size() ? result : std::vector{}; + } + + std::set animation_merge_indices_get(Document& document, const std::set& keys, int reference) + { + std::set result{}; + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + for (auto key : keys) + if (!is_window_group_key(key)) + result.insert(key); + else if (animations) + result.merge(animation_group_indices_get(*animations, window_group_id_from_key_get(key))); + result.erase(reference); + return result; + } + + void animation_overlay_reset(Document& document, const std::set& indices) + { + auto isOverlayDocument = document.overlayDocumentId == 0 || document.overlayDocumentId == document.tabId; + if (!isOverlayDocument || !indices.contains(document.overlayIndex)) return; + document.overlayIndex = -1; + document.overlayDocumentId = 0; + } + + void animation_groups_remove(Element& animations, const std::set& groupIds) + { + for (auto& item : animations.children) + if (item.type == ElementType::ANIMATION && groupIds.contains(item.groupId)) item.groupId = -1; + std::erase_if(animations.children, + [&](const Element& item) { return item.type == ElementType::GROUP && groupIds.contains(item.id); }); + } + + void animations_erase(Window& window, Document& document, const std::set& indices, const std::set& groupIds) + { + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + if (!animations) return; + animation_groups_remove(*animations, groupIds); + animation_overlay_reset(document, indices); + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + { + auto childIndex = animations_child_index_get(*animations, *it); + if (childIndex == -1) continue; + if (document.reference.animationIndex == *it) document.reference.animationIndex = -1; + animations->children.erase(animations->children.begin() + childIndex); + } + document.animation.selection.clear(); + window.selection.clear(); + } + + std::string animation_clipboard_text_get(Document& document, const Window& window) + { + std::string clipboardText{}; + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + if (!animations) return clipboardText; + int animationIndex{}; + for (const auto& item : animations->children) + { + if (item.type == ElementType::GROUP && window.selection.contains(item.id)) + clipboardText += element_to_string(item); + if (item.type != ElementType::ANIMATION) continue; + if (document.animation.selection.contains(animationIndex) || window.selection.contains(item.groupId)) + clipboardText += element_to_string(item); + ++animationIndex; + } + return clipboardText; + } + + void animations_insert(Window& window, Document& document, const std::string& text, int start, int targetGroupId, + StringType edit) + { + std::set indices{}; + std::set groupIds{}; + std::string errorString{}; + auto pasted = document.anm2; + if (!pasted.animations_deserialize(text, start, indices, &errorString, &groupIds)) + { + toast_log(Level::ERROR, TOAST_DESERIALIZE_ANIMATIONS_FAILED, errorString); + return; + } + + window_edit(document, window.changeType, localize.get(edit), + [&]() + { + document.anm2 = std::move(pasted); + if (targetGroupId != -1 && groupIds.empty()) + for (auto index : indices) + if (auto animation = document.anm2.element_get(ElementType::ANIMATION, index)) + animation->groupId = targetGroupId; + + document.animation.selection = groupIds.empty() ? indices : std::set{}; + window.selection = groupIds; + document.reference = {}; + window.newElementId = -1; + if (indices.empty()) return; + window.scrollQueued = *indices.rbegin(); + if (!groupIds.empty()) return; + document.reference = {*indices.rbegin()}; + if (indices.size() == 1) window.newElementId = *indices.rbegin(); + }); + } + + int animations_merge(Document& document, const AnimationMergeOptions& options, + const std::set* quickSelection = nullptr, + const std::set* quickGroupSelection = nullptr) + { + auto& anm2 = document.anm2; + int merged{-1}; + document.snapshots.anm2_push(localize.get(EDIT_MERGE_ANIMATIONS)); + if (options.selection.empty()) + { + auto selected = *quickSelection; + auto isQuickGroupMerge = quickGroupSelection && !quickGroupSelection->empty(); + auto animations = anm2.element_get(ElementType::ANIMATIONS); + auto count = animations ? animations_count_get(*animations) : 0; + animation_overlay_reset(document, selected); + + if (selected.size() == 1 && !isQuickGroupMerge && *selected.begin() != count - 1) + selected.insert(*selected.begin() + 1); + if (selected.size() > 1) + merged = anm2.animations_merge(*selected.begin(), selected); + else if (selected.size() == 1 && isQuickGroupMerge) + merged = *selected.begin(); + if (merged != -1 && isQuickGroupMerge && animations) animation_groups_remove(*animations, *quickGroupSelection); + } + else + { + auto mergeSelection = animation_merge_indices_get(document, options.selection, options.reference); + if (mergeSelection.empty()) return -1; + animation_overlay_reset(document, mergeSelection); + merged = anm2.animations_merge(options.reference, mergeSelection, options.type, options.isDeleteAnimationsAfter); + } + + if (merged == -1) return -1; + document.animation.selection = {merged}; + document.reference = {merged}; + document.change(Document::ANIMATIONS); + return merged; + } + + Element animation_track_container_shell_copy(const Element* source, const TrackContainer& row) + { + auto destination = element_make(row.container); + if (!source) return destination; + + auto nextGroupId = element_child_next_id_get(*source, ElementType::GROUP); + std::set copiedTrackIds{}; + auto track_push = [&](const Element& track, int groupId) + { + if (track.type != row.track || !copiedTrackIds.insert(track_id_get(track)).second) return; + auto item = element_make(row.track); + item.*(row.id) = track.*(row.id); + item.groupId = track.groupId != -1 ? track.groupId : groupId; + item.isVisible = track.isVisible; + destination.children.push_back(item); + }; + + for (const auto& sourceItem : source->children) + { + if (sourceItem.type != ElementType::GROUP) + { + track_push(sourceItem, -1); + continue; + } + auto group = element_make(ElementType::GROUP); + group.id = sourceItem.id >= 0 ? sourceItem.id : nextGroupId++; + group.name = sourceItem.name; + group.isExpanded = sourceItem.isExpanded; + group.isVisible = sourceItem.isVisible; + group.children.push_back(root_animation_make()); + destination.children.push_back(group); + for (const auto& child : sourceItem.children) + track_push(child, group.id); + } + return destination; + } + + AnimationDropZone animation_drop_zone_get(ImVec2 min, ImVec2 max) + { + auto zoneHeight = (max.y - min.y) * DROP_ZONE_FRACTION; + auto mouseY = ImGui::GetIO().MousePos.y; + if (mouseY < min.y + zoneHeight) return AnimationDropZone::BEFORE; + if (mouseY >= max.y - zoneHeight) return AnimationDropZone::AFTER; + return AnimationDropZone::INSIDE; + } + + void animation_items_move(Window& window, Document& document, const std::vector& items, + int targetChildIndex, int targetGroupId) + { + auto animations = window_container_get(window, document); + if (!animations) return; + + auto groupIds = 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 && animations_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 && draggedGroupIds.contains(item.id)) childIndices.push_back(i); + if (item.type != ElementType::ANIMATION) continue; + auto isGroupDragged = draggedGroupIds.contains(item.groupId); + if (draggedAnimationIds.contains(animationIndex) && !isGroupDragged) + { + item.groupId = groupId; + directAnimationChildIndices.insert(i); + } + if (isGroupDragged || draggedAnimationIds.contains(animationIndex)) childIndices.push_back(i); + ++animationIndex; + } + + auto movedChildIndices = vector::move_indices_to_position(animations->children, childIndices, targetChildIndex); + if (movedChildIndices.empty()) return; + + document.animation.selection.clear(); + window.selection = draggedGroupIds; + auto moved = movedChildIndices.begin(); + for (auto source = childIndices.begin(); source != childIndices.end() && moved != movedChildIndices.end(); + ++source, ++moved) + if (directAnimationChildIndices.contains(*source)) + if (auto index = animation_index_from_child_index_get(*animations, *moved); index != -1) + document.animation.selection.insert(index); + } + + void animation_move_command_push(Window& window, Manager& manager, std::vector items, + int targetGroupId, std::function target_child_index_get) + { + if (items.empty()) return; + manager.command_push( + {manager.selected, [&window, items, targetGroupId, target_child_index_get](Manager&, Document& document) + { + auto animations = window_container_get(window, document); + if (!animations) return; + window_edit( + document, window.changeType, localize.get(EDIT_MOVE_ANIMATIONS), [&]() + { animation_items_move(window, document, items, target_child_index_get(*animations), targetGroupId); }); + }}); + } + + void animation_drag_drop_source_update(Document& document, const Window& window, AnimationDragDropItem fallback) + { + if (!ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) return; + + static std::vector items{}; + items.clear(); + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + auto isFallbackSelected = fallback.type == AnimationDragDropType::GROUP + ? window.selection.contains(fallback.id) + : document.animation.selection.contains(fallback.id); + if (animations && isFallbackSelected) + { + auto groupIds = animation_group_ids_get(*animations); + for (auto groupId : window.selection) + if (groupIds.contains(groupId)) items.push_back({AnimationDragDropType::GROUP, groupId}); + for (auto animationIndex : document.animation.selection) + if (animations_child_index_get(*animations, animationIndex) != -1) + items.push_back({AnimationDragDropType::ANIMATION, animationIndex}); + } + if (items.empty() && fallback.id >= 0) items.push_back(fallback); + ImGui::SetDragDropPayload(ANIMATION_DRAG_DROP, items.data(), items.size() * sizeof(AnimationDragDropItem)); + ImGui::EndDragDropSource(); + } + + std::vector animation_drag_drop_target_items_get() + { + auto payload = ImGui::AcceptDragDropPayload(ANIMATION_DRAG_DROP, ImGuiDragDropFlags_AcceptBeforeDelivery | + ImGuiDragDropFlags_AcceptNoDrawDefaultRect); + if (!payload || payload->DataSize % (int)sizeof(AnimationDragDropItem) != 0) return {}; + auto items = static_cast(payload->Data); + return {items, items + payload->DataSize / sizeof(AnimationDragDropItem)}; + } + + bool animation_group_drag_drop_update(Window& window, Manager& manager, int groupId, ImVec2 itemMin, ImVec2 itemMax) + { + if (!ImGui::BeginDragDropTarget()) return false; + auto items = animation_drag_drop_target_items_get(); + auto isDelivered = false; + if (!items.empty()) + { + auto dropZone = animation_drop_zone_get(itemMin, itemMax); + auto isGroupDragged = std::ranges::any_of(items, [](const AnimationDragDropItem& item) + { return item.type == AnimationDragDropType::GROUP; }); + auto isDropIntoGroup = dropZone == AnimationDropZone::INSIDE && !isGroupDragged; + if (isDropIntoGroup) + drop_box_draw(ImGui::GetWindowDrawList(), itemMin, itemMax); + else + drop_line_draw(ImGui::GetWindowDrawList(), itemMin, itemMax, dropZone != AnimationDropZone::BEFORE); + + isDelivered = ImGui::GetDragDropPayload()->IsDelivery(); + if (isDelivered) + { + auto targetDropZone = + dropZone == AnimationDropZone::INSIDE && !isDropIntoGroup ? AnimationDropZone::AFTER : dropZone; + animation_move_command_push( + window, manager, items, isDropIntoGroup ? groupId : -1, [groupId, targetDropZone](const Element& animations) + { return animation_group_child_insert_index_get(animations, groupId, targetDropZone); }); + } + } + ImGui::EndDragDropTarget(); + return isDelivered; + } + + bool animation_row_drag_drop_update(Window& window, Manager& manager, Document& document, const Element& animation, + int index) + { + animation_drag_drop_source_update(document, window, {AnimationDragDropType::ANIMATION, index}); + if (!ImGui::BeginDragDropTarget()) return false; + + auto items = animation_drag_drop_target_items_get(); + auto isDelivered = false; + if (!items.empty()) + { + auto itemMin = ImGui::GetItemRectMin(); + auto itemMax = ImGui::GetItemRectMax(); + auto isDropAfter = is_drop_after(itemMin, itemMax); + drop_line_draw(ImGui::GetWindowDrawList(), itemMin, itemMax, isDropAfter); + isDelivered = ImGui::GetDragDropPayload()->IsDelivery(); + if (isDelivered) + animation_move_command_push(window, manager, items, animation.groupId, + [targetIndex = index + (isDropAfter ? 1 : 0)](const Element& animations) + { return animations_child_insert_index_get(animations, targetIndex); }); + } + ImGui::EndDragDropTarget(); + return isDelivered; + } + + void animation_group_set_push(Manager& manager, int groupId, StringType edit, std::optional name, + std::optional isExpanded) + { + manager.command_push({manager.selected, [groupId, edit, name, isExpanded](Manager&, Document& document) + { + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + auto group = animations ? child_id_get(*animations, ElementType::GROUP, groupId) : nullptr; + if (!group || (name.value_or(group->name) == group->name && + isExpanded.value_or(group->isExpanded) == group->isExpanded)) + return; + window_edit(document, Document::ANIMATIONS, localize.get(edit), + [&]() + { + group->name = name.value_or(group->name); + group->isExpanded = isExpanded.value_or(group->isExpanded); + }); + }}); + } + + void animation_group_draw(Window& window, Manager& manager, Resources& resources, Document& document, Element& group, + int arrowSelectionId, bool& isRowsDone) + { + auto& groupSelection = window.selection; + auto container = window_container_get(window, document); + auto renameKey = window_group_key_get(group.id); + auto isRenaming = window.renameId == renameKey; + if (window.renameQueued == renameKey) + { + window.renameState = RENAME_FORCE_EDIT; + window.renameQueued = -1; + } + + ImGui::PushID("Animation Group"); + ImGui::PushID(group.id); + ImGui::SetNextItemOpen(group.isExpanded, ImGuiCond_Always); + auto tree = + tree_node_input_text(group.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group.name, + std::format("###Document #{} Animation Group #{}", manager.selected, group.id), + isRenaming ? window.renameText : group.name, groupSelection.contains(group.id), + ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth, window.renameState); + auto itemMin = ImGui::GetItemRectMin(); + auto itemMax = ImGui::GetItemRectMax(); + if (tree.isRenameStarted) + { + window.renameId = renameKey; + window.renameText = group.name; + } + else if (tree.isRenameFinished) + { + if (isRenaming) animation_group_set_push(manager, group.id, EDIT_RENAME_GROUP, window.renameText, std::nullopt); + window.renameId = -1; + window.renameText.clear(); + } + if (tree.isOpen != group.isExpanded && !is_drag_drop_active() && !ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + animation_group_set_push(manager, group.id, EDIT_TOGGLE_GROUP_EXPANDED, std::nullopt, tree.isOpen); + + if (tree.isClicked) + { + auto isCtrl = ImGui::GetIO().KeyCtrl; + auto& selection = document.animation.selection; + auto isDeselected = isCtrl && groupSelection.contains(group.id); + if (!isCtrl) + { + selection.clear(); + groupSelection.clear(); + } + if (isDeselected) + groupSelection.erase(group.id); + else + groupSelection.insert(group.id); + if (isDeselected ? selection.empty() && groupSelection.empty() : !isCtrl || selection.empty()) + { + document.animation.reference = -1; + document.reference = {}; + document.frames.clear(); + } + } + + animation_drag_drop_source_update(document, window, {AnimationDragDropType::GROUP, group.id}); + isRowsDone = animation_group_drag_drop_update(window, manager, group.id, itemMin, itemMax); + + if (tree.isOpen) + { + int animationIndex{}; + for (auto& animation : container->children) + if (animation.type == ElementType::ANIMATION && !isRowsDone) + { + if (animation.groupId == group.id) + isRowsDone = window_row_draw(window, manager, resources, document, animation, animationIndex, + animationIndex, arrowSelectionId); + ++animationIndex; + } + ImGui::TreePop(); + } + ImGui::PopID(); + ImGui::PopID(); + } + + Window animations_window_register() + { + Window window{}; + window.title = LABEL_ANIMATIONS_WINDOW; + window.isOpen = &Settings::windowIsAnimations; + window.changeType = Document::ANIMATIONS; + window.containerType = ElementType::ANIMATIONS; + window.elementType = ElementType::ANIMATION; + window.childLabel = "##Animations Child"; + window.renameEdit = SNAPSHOT_RENAME_ANIMATION; + window.flags = WINDOW_ADD | WINDOW_DUPLICATE | WINDOW_MERGE | WINDOW_GROUP | WINDOW_REMOVE | WINDOW_DEFAULT | + WINDOW_CUT | WINDOW_COPY | WINDOW_PASTE | WINDOW_RENAME; + window.footer = {{WINDOW_ADD, WINDOW_DUPLICATE, WINDOW_MERGE, WINDOW_REMOVE, WINDOW_DEFAULT}}; + window.tooltips = {{WINDOW_ADD, TOOLTIP_ADD_ANIMATION}, + {WINDOW_DUPLICATE, TOOLTIP_DUPLICATE_ANIMATION}, + {WINDOW_MERGE, TOOLTIP_OPEN_MERGE_POPUP}, + {WINDOW_REMOVE, TOOLTIP_REMOVE_ANIMATION}, + {WINDOW_DEFAULT, TOOLTIP_SET_DEFAULT_ANIMATION}}; + window.enabled = { + {WINDOW_MERGE, + [](Window& window, Document& document) { return !animation_selected_indices_get(document, window).empty(); }}, + {WINDOW_GROUP, [](Window&, Document& document) { return !animation_groupable_indices_get(document).empty(); }}}; + window.popup = PopupHelper(LABEL_ANIMATIONS_MERGE_POPUP); + window.storage_get = [](Document& document) -> Storage& { return document.animation; }; + window.element_get = [](Anm2& anm2, int index) { return anm2.element_get(ElementType::ANIMATION, index); }; + window.element_key_get = [](const Element&, int index) { return index; }; + window.row_font_get = [](Document& document, const Element& animation, int index) + { + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + auto isDefault = animations && animations->defaultAnimation == animation.name; + auto isReferenced = document.reference.animationIndex == index; + return isDefault && isReferenced ? font::BOLD_ITALICS + : isDefault ? font::BOLD + : isReferenced ? font::ITALICS + : font::REGULAR; + }; + window.row_select = [](Window& window, Document& document, int index) + { + auto& io = ImGui::GetIO(); + if (!io.KeyCtrl && !io.KeyShift) window.selection.clear(); + document.reference = {index}; + document.frames.clear(); + }; + window.rename_finish = [](Document& document, Element& animation, int, int count) + { + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + if (animations && count == 1) animations->defaultAnimation = animation.name; + }; + window.tooltip_draw = [](Document& document, Resources& resources, const Element& animation) + { + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + window_tooltip_name_draw(resources, animation.name); + if (animations && animations->defaultAnimation == animation.name) + { + ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); + ImGui::TextUnformatted(localize.get(BASIC_DEFAULT)); + ImGui::PopFont(); + } + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_LENGTH), std::make_format_args(animation.frameNum)).c_str()); + auto loopLabel = localize.get(animation.isLoop ? BASIC_YES : BASIC_NO); + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_LOOP), std::make_format_args(loopLabel)).c_str()); + }; + window.row_drag_drop_update = animation_row_drag_drop_update; + window.rows_update = [](Window& window, Manager& manager, Settings& settings, Resources& resources, + Clipboard& clipboard, Document& document) + { + auto container = window_container_get(window, document); + if (!container) return; + auto groupIds = animation_group_ids_get(*container); + std::erase_if(window.selection, [&](int groupId) { return !groupIds.contains(groupId); }); + + std::vector visibleIds{}; + window.order.clear(); + int animationIndex{}; + for (auto& item : container->children) + { + if (item.type == ElementType::GROUP && item.isExpanded) + visibleIds.insert_range(visibleIds.end(), animation_group_indices_get(*container, item.id)); + if (item.type != ElementType::ANIMATION) continue; + if (!is_animation_grouped(groupIds, item)) visibleIds.push_back(animationIndex); + window.order.push_back(animationIndex++); + } + + auto arrowSelectionId = window_selection_start(window, document, visibleIds); + if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + { + document.animation.selection = std::set(window.order.begin(), window.order.end()); + window.selection = groupIds; + } + + auto isRowsDone = false; + animationIndex = 0; + for (auto& item : container->children) + { + if (isRowsDone) break; + if (item.type == ElementType::GROUP) + animation_group_draw(window, manager, resources, document, item, arrowSelectionId, isRowsDone); + if (item.type != ElementType::ANIMATION) continue; + if (!is_animation_grouped(groupIds, item)) + isRowsDone = window_row_draw(window, manager, resources, document, item, animationIndex, animationIndex, + arrowSelectionId); + ++animationIndex; + } + window_selection_finish(window, manager, settings, clipboard, document, arrowSelectionId); + }; + window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto& selection = document.animation.selection; + auto animations = window_container_get(window, document); + if (!animations) return; + + window_edit(document, window.changeType, localize.get(EDIT_ADD_ANIMATION), + [&]() + { + auto groupIds = animation_group_ids_get(*animations); + auto targetGroupId = window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) + ? *window.selection.begin() + : -1; + + auto animation = element_make(ElementType::ANIMATION); + animation.name = localize.get(TEXT_NEW_ANIMATION); + animation.children.push_back(root_animation_make()); + auto referenceAnimation = + document.anm2.element_get(ElementType::ANIMATION, document.reference.animationIndex); + for (const auto& row : TRACK_CONTAINERS) + animation.children.push_back(animation_track_container_shell_copy( + referenceAnimation ? child_first_get(*referenceAnimation, row.container) : nullptr, row)); + animation.children.push_back(element_make(ElementType::TRIGGERS)); + + auto count = animations_count_get(*animations); + auto groupIndices = + targetGroupId != -1 ? animation_group_indices_get(*animations, targetGroupId) : std::set{}; + auto index = !selection.empty() ? std::min(*selection.rbegin() + 1, count) + : !groupIndices.empty() ? std::min(*groupIndices.rbegin() + 1, count) + : count; + auto selected = selection.empty() + ? nullptr + : document.anm2.element_get(ElementType::ANIMATION, *selection.rbegin()); + if (selected && groupIds.contains(selected->groupId)) animation.groupId = selected->groupId; + if (selection.empty()) animation.groupId = targetGroupId; + if (count == 0) animations->defaultAnimation = animation.name; + + animations->children.insert(animations->children.begin() + + animations_child_insert_index_get(*animations, index), + animation); + selection = {index}; + window.selection.clear(); + document.reference = {index}; + window.newElementId = index; + window.scrollQueued = index; + }); + }; + window.remove = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto selection = std::set(document.animation.selection.begin(), document.animation.selection.end()); + auto groupSelection = window.selection; + window_edit(document, window.changeType, + localize.get(groupSelection.empty() ? EDIT_REMOVE_ANIMATIONS : EDIT_REMOVE_GROUP), + [&]() { animations_erase(window, document, selection, groupSelection); }); + }; + window.cut = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) + { + if (auto text = animation_clipboard_text_get(document, window); !text.empty()) clipboard.set(text); + auto selectedIndices = animation_selected_indices_get(document, window); + auto groupSelection = window.selection; + window_edit(document, window.changeType, localize.get(EDIT_CUT_ANIMATIONS), + [&]() { animations_erase(window, document, selectedIndices, groupSelection); }); + }; + window.copy = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) + { + if (auto text = animation_clipboard_text_get(document, window); !text.empty()) clipboard.set(text); + }; + window.duplicate = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto animations = window_container_get(window, document); + auto text = animation_clipboard_text_get(document, window); + if (!animations || text.empty()) return; + auto selectedIndices = animation_selected_indices_get(document, window); + auto count = animations_count_get(*animations); + animations_insert(window, document, text, + selectedIndices.empty() ? count : std::min(*selectedIndices.rbegin() + 1, count), -1, + EDIT_DUPLICATE_ANIMATIONS); + }; + window.paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) + { + auto animations = window_container_get(window, document); + if (clipboard.is_empty() || !animations) return; + auto& selection = document.animation.selection; + auto count = animations_count_get(*animations); + auto groupIds = animation_group_ids_get(*animations); + auto targetGroupId = + selection.empty() && window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) + ? *window.selection.begin() + : -1; + auto groupIndices = + targetGroupId != -1 ? animation_group_indices_get(*animations, targetGroupId) : std::set{}; + auto start = !selection.empty() ? *selection.rbegin() + 1 + : !groupIndices.empty() ? std::min(*groupIndices.rbegin() + 1, count) + : count; + animations_insert(window, document, clipboard.get(), start, targetGroupId, EDIT_PASTE_ANIMATIONS); + }; + window.merge = [](Window& window, Manager&, Settings& settings, Document& document, Clipboard&) + { + auto& mergeSelection = document.merge.selection; + auto quickSelection = animation_selected_indices_get(document, window); + auto quickGroupSelection = window.selection; + auto merged = animations_merge(document, + {.selection = mergeSelection, + .reference = document.merge.reference, + .type = (merge::Type)settings.mergeType, + .isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter}, + &quickSelection, &quickGroupSelection); + if (merged != -1) + { + window.scrollQueued = merged; + window.selection.clear(); + } + mergeSelection.clear(); + }; + window.merge_open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + if (document.animation.selection.empty()) return; + window.popup.open(); + document.merge.selection.clear(); + document.merge.reference = *document.animation.selection.begin(); + }; + window.group = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto targetIndices = animation_groupable_indices_get(document); + auto animations = window_container_get(window, document); + if (targetIndices.empty() || !animations) return; + + window_edit(document, window.changeType, localize.get(EDIT_GROUP_ITEMS), + [&]() + { + std::set targetSet(targetIndices.begin(), targetIndices.end()); + auto group = element_make(ElementType::GROUP); + group.id = element_child_next_id_get(*animations, ElementType::GROUP); + group.name = localize.get(TEXT_NEW_GROUP); + for (auto index : targetSet) + document.anm2.element_get(ElementType::ANIMATION, index)->groupId = group.id; + animations->children.insert(animations->children.begin() + + animations_child_index_get(*animations, *targetSet.begin()), + group); + document.animation.selection = targetSet; + window.selection = {group.id}; + document.reference = {*targetSet.begin()}; + window.scrollQueued = *targetSet.begin(); + }); + }; + window.default_set = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto animations = window_container_get(window, document); + auto animation = document.anm2.element_get(ElementType::ANIMATION, *document.animation.selection.begin()); + if (!animations || !animation) return; + window_edit(document, window.changeType, localize.get(EDIT_DEFAULT_ANIMATION), + [&]() { animations->defaultAnimation = animation->name; }); + }; + window.body_update = + [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard&, Document& document) + { + auto& mergeSelection = document.merge.selection; + auto mergeReference = document.merge.reference; + + window.popup.trigger(); + if (!ImGui::BeginPopupModal(window.popup.label(), &window.popup.isOpen, ImGuiWindowFlags_NoResize)) return; + + struct AnimationMergeCandidate + { + int key{}; + std::string label{}; + }; + std::vector candidates{}; + auto animations = window_container_get(window, document); + auto groupIds = animations ? animation_group_ids_get(*animations) : std::set{}; + static const Element EMPTY{}; + auto candidate_animation_push = [&](const Element& animation, int animationIndex, bool isGrouped) + { + if (animationIndex != mergeReference) + candidates.push_back({animationIndex, isGrouped ? std::format(" {}", animation.name) : animation.name}); + }; + + int animationIndex{}; + for (const auto& item : (animations ? *animations : EMPTY).children) + { + if (item.type == ElementType::GROUP) + { + auto groupIndices = animation_group_indices_get(*animations, item.id); + groupIndices.erase(mergeReference); + if (groupIndices.empty()) continue; + candidates.push_back({window_group_key_get(item.id), + item.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : item.name}); + int groupAnimationIndex{}; + for (const auto& animation : animations->children) + if (animation.type == ElementType::ANIMATION) + { + if (animation.groupId == item.id) candidate_animation_push(animation, groupAnimationIndex, true); + ++groupAnimationIndex; + } + } + if (item.type != ElementType::ANIMATION) continue; + if (!is_animation_grouped(groupIds, item)) candidate_animation_push(item, animationIndex, false); + ++animationIndex; + } + + auto footerSize = footer_size_get(); + auto optionsSize = child_size_get(MERGE_OPTIONS_ROWS); + auto deleteAfterSize = child_size_get(); + auto animationsSize = + ImVec2(0, ImGui::GetContentRegionAvail().y - (optionsSize.y + deleteAfterSize.y + footerSize.y + + ImGui::GetStyle().ItemSpacing.y * MERGE_POPUP_CHILD_COUNT)); + + if (ImGui::BeginChild(localize.get(LABEL_ANIMATIONS_CHILD), animationsSize, ImGuiChildFlags_Borders)) + { + std::vector candidateKeys{}; + for (const auto& candidate : candidates) + candidateKeys.push_back(candidate.key); + mergeSelection.set_index_map(&candidateKeys); + mergeSelection.start(candidates.size()); + for (int i = 0; i < (int)candidates.size(); ++i) + { + ImGui::PushID(candidates[i].key); + ImGui::SetNextItemSelectionUserData(i); + ImGui::Selectable(candidates[i].label.c_str(), mergeSelection.contains(candidates[i].key)); + ImGui::PopID(); + } + mergeSelection.finish(); + mergeSelection.set_index_map(nullptr); + } + ImGui::EndChild(); + + if (ImGui::BeginChild("##Merge Options", optionsSize, ImGuiChildFlags_Borders)) + { + auto size = ImVec2(optionsSize.x * MERGE_OPTIONS_HALF, optionsSize.y - ImGui::GetStyle().WindowPadding.y * 2); + if (ImGui::BeginChild("##Merge Options 1", size)) + { + ImGui::RadioButton(localize.get(LABEL_APPEND_FRAMES), &settings.mergeType, merge::APPEND); + ImGui::RadioButton(localize.get(LABEL_PREPEND_FRAMES), &settings.mergeType, merge::PREPEND); + } + ImGui::EndChild(); + ImGui::SameLine(); + if (ImGui::BeginChild("##Merge Options 2", size)) + { + ImGui::RadioButton(localize.get(LABEL_REPLACE_FRAMES), &settings.mergeType, merge::REPLACE); + ImGui::RadioButton(localize.get(LABEL_IGNORE_FRAMES), &settings.mergeType, merge::IGNORE); + } + ImGui::EndChild(); + } + ImGui::EndChild(); + + if (ImGui::BeginChild("##Merge Delete After", deleteAfterSize, ImGuiChildFlags_Borders)) + ImGui::Checkbox(localize.get(LABEL_DELETE_ANIMATIONS_AFTER), &settings.mergeIsDeleteAnimationsAfter); + ImGui::EndChild(); + + auto result = window_popup_buttons_draw( + manager, localize.get(LABEL_MERGE), + !animation_merge_indices_get(document, mergeSelection, mergeReference).empty(), LABEL_CLOSE); + if (result == PopupButton::CONFIRM) + manager.command_push( + {manager.selected, + [options = AnimationMergeOptions{.selection = mergeSelection, + .reference = mergeReference, + .type = (merge::Type)settings.mergeType, + .isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter}]( + Manager&, Document& document) { animations_merge(document, options); }}); + if (result != PopupButton::NONE) + { + mergeSelection.clear(); + window.popup.close(); + } + ImGui::EndPopup(); + }; + window.post_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) + { + auto isNext = shortcut(manager.chords[SHORTCUT_NEXT_ANIMATION], shortcut::GLOBAL); + auto isPrevious = shortcut(manager.chords[SHORTCUT_PREVIOUS_ANIMATION], shortcut::GLOBAL); + auto animations = window_container_get(window, document); + auto count = animations ? animations_count_get(*animations) : 0; + if ((!isPrevious && !isNext) || count <= 0) return; + + auto& reference = document.reference; + reference.animationIndex = std::clamp(reference.animationIndex + (isNext ? 1 : -1), 0, count - 1); + document.animation.selection = {reference.animationIndex}; + window.scrollQueued = reference.animationIndex; + }; + return window; + } +} diff --git a/src/imgui/window/items.cpp b/src/imgui/window/items.cpp new file mode 100644 index 0000000..8c609f0 --- /dev/null +++ b/src/imgui/window/items.cpp @@ -0,0 +1,159 @@ +#include "window.hpp" + +#include + +#include "util/imgui/input.hpp" +#include "util/imgui/layout.hpp" + +using namespace anm2ed::types; + +namespace anm2ed::imgui +{ + constexpr int ITEM_PROPERTIES_ROWS = 2; + + void item_tooltip_draw(Resources& resources, const Element& element) + { + window_tooltip_name_draw(resources, element.name); + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(element.id)).c_str()); + } + + void item_properties_popup_update(Window& window, Manager& manager, Document& document, StringType nameTooltip, + const std::function& fields_draw) + { + auto& popup = manager.itemPropertiesPopups[track_container_get(window.elementType) - TRACK_CONTAINERS]; + auto reference = window.storage_get(document).reference; + + popup.trigger(); + if (ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) + { + if (ImGui::BeginChild("##Child", child_size_get(ITEM_PROPERTIES_ROWS), ImGuiChildFlags_Borders)) + { + if (popup.isJustOpened) ImGui::SetKeyboardFocusHere(); + input_text_string(localize.get(BASIC_NAME), &manager.itemEdit.name); + ImGui::SetItemTooltip("%s", localize.get(nameTooltip)); + fields_draw(manager.itemEdit); + } + ImGui::EndChild(); + + auto result = window_popup_buttons_draw(manager, localize.get(reference == -1 ? BASIC_ADD : BASIC_CONFIRM)); + if (result == PopupButton::CONFIRM) window_element_apply_push(window, manager, manager.itemEdit, reference); + if (result != PopupButton::NONE) popup.close(); + ImGui::EndPopup(); + } + popup.end(); + } + + Window item_window_make(StringType title, bool Settings::* isOpen, Document::ChangeType changeType, + ElementType elementType, const char* childLabel, StringType addTooltip, + StringType removeUnusedTooltip) + { + Window window{}; + window.title = title; + window.isOpen = isOpen; + window.changeType = changeType; + window.containerType = ELEMENT_CONTAINERS[(int)elementType]; + window.elementType = elementType; + window.childLabel = childLabel; + window.tooltips = {{WINDOW_ADD, addTooltip}, {WINDOW_REMOVE_UNUSED, removeUnusedTooltip}}; + window.footer = {{WINDOW_ADD, WINDOW_REMOVE_UNUSED}}; + window.flags = WINDOW_ADD | WINDOW_REMOVE_UNUSED | WINDOW_COPY | WINDOW_PASTE; + window.tooltip_draw = [](Document&, Resources& resources, const Element& element) + { item_tooltip_draw(resources, element); }; + window.properties_open = [elementType](Manager& manager, int id) { manager.item_properties_open(elementType, id); }; + return window; + } + + Window layers_window_register() + { + auto window = + item_window_make(LABEL_LAYERS_WINDOW, &Settings::windowIsLayers, Document::LAYERS, ElementType::LAYER_ELEMENT, + "##Layers Child", TOOLTIP_ADD_LAYER, TOOLTIP_REMOVE_UNUSED_LAYERS); + window.addEdit = EDIT_ADD_LAYER; + window.propertiesEdit = EDIT_SET_LAYER_PROPERTIES; + window.pasteEdit = EDIT_PASTE_LAYERS; + window.removeUnusedEdit = EDIT_REMOVE_UNUSED_LAYERS; + window.deserializeFailedToast = TOAST_DESERIALIZE_LAYERS_FAILED; + window.flags |= WINDOW_PROPERTIES; + window.storage_get = [](Document& document) -> Storage& { return document.layer; }; + window.row_label_get = [](Document&, const Element& layer) + { + return std::vformat(localize.get(FORMAT_LAYER), std::make_format_args(layer.id, layer.name, layer.spritesheetId)); + }; + window.tooltip_draw = [](Document&, Resources& resources, const Element& layer) + { + item_tooltip_draw(resources, layer); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_SPRITESHEET_ID), std::make_format_args(layer.spritesheetId)).c_str()); + }; + window.popup_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) + { + item_properties_popup_update(window, manager, document, TOOLTIP_ITEM_NAME, + [&](Element& layer) + { + combo_id_mapped(localize.get(LABEL_SPRITESHEET), &layer.spritesheetId, + document.spritesheet.ids, document.spritesheet.labels); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SPRITESHEET)); + }); + }; + return window; + } + + Window nulls_window_register() + { + auto window = + item_window_make(LABEL_NULLS_WINDOW, &Settings::windowIsNulls, Document::NULLS, ElementType::NULL_ELEMENT, + "##Nulls Child", TOOLTIP_ADD_NULL, TOOLTIP_REMOVE_UNUSED_NULLS); + window.addEdit = EDIT_ADD_NULL; + window.propertiesEdit = EDIT_SET_NULL_PROPERTIES; + window.pasteEdit = EDIT_PASTE_NULLS; + window.removeUnusedEdit = EDIT_REMOVE_UNUSED_NULLS; + window.deserializeFailedToast = TOAST_DESERIALIZE_NULLS_FAILED; + window.flags |= WINDOW_PROPERTIES | WINDOW_REFERENCE_ITALIC; + window.storage_get = [](Document& document) -> Storage& { return document.null; }; + window.row_label_get = [](Document&, const Element& null) + { return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(null.id, null.name)); }; + window.popup_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) + { + item_properties_popup_update(window, manager, document, TOOLTIP_NULL_NAME, + [](Element& null) + { + ImGui::Checkbox(localize.get(LABEL_RECT), &null.isShowRect); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_RECT)); + }); + }; + return window; + } + + Window events_window_register() + { + auto window = + item_window_make(LABEL_EVENTS_WINDOW, &Settings::windowIsEvents, Document::EVENTS, ElementType::EVENT_ELEMENT, + "##Events Child", TOOLTIP_ADD_EVENT, TOOLTIP_REMOVE_UNUSED_EVENTS); + window.addEdit = EDIT_ADD_EVENT; + window.renameEdit = EDIT_RENAME_EVENT; + window.pasteEdit = EDIT_PASTE_EVENTS; + window.removeUnusedEdit = EDIT_REMOVE_UNUSED_EVENTS; + window.deserializeFailedToast = TOAST_DESERIALIZE_EVENTS_FAILED; + window.flags |= WINDOW_RENAME; + window.properties_open = {}; + window.storage_get = [](Document& document) -> Storage& { return document.event; }; + window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto event = element_make(ElementType::EVENT_ELEMENT); + event.name = localize.get(TEXT_NEW_EVENT); + auto events = window_container_get(window, document); + if (!events) return; + window_edit(document, window.changeType, localize.get(window.addEdit), + [&]() + { + event.id = element_child_next_id_get(*events, ElementType::EVENT_ELEMENT); + events->children.push_back(event); + auto& storage = window.storage_get(document); + storage.selection = {event.id}; + storage.reference = event.id; + window.newElementId = event.id; + }); + }; + return window; + } +} diff --git a/src/imgui/window/regions.cpp b/src/imgui/window/regions.cpp new file mode 100644 index 0000000..880722b --- /dev/null +++ b/src/imgui/window/regions.cpp @@ -0,0 +1,546 @@ +#include "window.hpp" + +#include +#include + +#include "math.hpp" +#include "path.hpp" +#include "toast.hpp" +#include "util/imgui/draw.hpp" +#include "util/imgui/input.hpp" +#include "util/imgui/layout.hpp" +#include "vector.hpp" +#include "working_directory.hpp" + +using namespace anm2ed::resource; +using namespace anm2ed::types; +using namespace anm2ed::util; +using namespace glm; + +namespace anm2ed::imgui +{ + constexpr int REGION_CARD_LINES = 2; + constexpr int REGION_POPUP_ROWS = 5; + constexpr const char* REGION_DRAG_DROP = "Region Drag Drop"; + constexpr const char* REGION_EXPORT_NAME_DEFAULT = "region"; + constexpr const char* PNG_EXTENSION = ".png"; + constexpr ImVec2 DRAG_TOOLTIP_OFFSET = ImVec2(16.0f, 16.0f); + + constexpr StringType ORIGIN_LABELS[] = {LABEL_REGION_ORIGIN_CUSTOM, LABEL_REGION_ORIGIN_TOP_LEFT, + LABEL_REGION_ORIGIN_CENTER}; + constexpr Origin ORIGIN_COMBO_ORDER[] = {Origin::TOP_LEFT, Origin::CENTER, Origin::CUSTOM}; + + struct RegionExportOptions + { + int spritesheetId{-1}; + int regionId{-1}; + std::filesystem::path path{}; + bool isMakeSpritesheet{}; + bool isRemoveCurrent{}; + }; + + void region_pivot_apply(Element& region) + { + if (region.origin == Origin::TOP_LEFT) region.pivot = {}; + if (region.origin == Origin::CENTER) region.pivot = region.size * 0.5f; + } + + Element* region_spritesheet_get(Document& document) + { + return document.anm2.element_get(ElementType::SPRITESHEET, document.spritesheet.reference); + } + + int region_insert_index_get(Document& document) + { + auto spritesheet = region_spritesheet_get(document); + auto& storage = document.region; + int index = spritesheet ? (int)spritesheet->children.size() : 0; + for (int i = 0; spritesheet && i < (int)spritesheet->children.size(); i++) + { + const auto& child = spritesheet->children[i]; + if (child.type == ElementType::REGION && + (storage.selection.contains(child.id) || (storage.selection.empty() && storage.reference == child.id))) + index = i + 1; + } + return index; + } + + WindowCardImage region_image_get(Document& document, Resources& resources, const Element& region) + { + auto texture = document.texture_get(document.spritesheet.reference); + auto isValid = texture && texture->is_valid(); + if (!isValid) return {.texture = &resources.icons[icon::NONE], .size = region.size}; + return {.texture = texture, + .size = region.size, + .uvMin = region.crop / vec2(texture->size), + .uvMax = (region.crop + region.size) / vec2(texture->size), + .isValid = true}; + } + + bool region_pixels_get(const Element& region, const Texture& texture, std::vector& pixels, ivec2& size) + { + auto minPoint = ivec2(glm::min(region.crop, region.crop + region.size)); + size = ivec2(glm::max(region.crop, region.crop + region.size)) - minPoint; + if (size.x <= 0 || size.y <= 0 || texture.size.x <= 0 || texture.size.y <= 0 || texture.pixels.empty()) + return false; + + pixels.assign((size_t)size.x * size.y * texture::CHANNELS, 0); + for (int y = 0; y < size.y; y++) + for (int x = 0; x < size.x; x++) + { + auto source = minPoint + ivec2(x, y); + if (source.x < 0 || source.y < 0 || source.x >= texture.size.x || source.y >= texture.size.y) continue; + std::copy_n(texture.pixels.data() + ((size_t)source.y * texture.size.x + source.x) * texture::CHANNELS, + texture::CHANNELS, pixels.data() + ((size_t)y * size.x + x) * texture::CHANNELS); + } + return true; + } + + bool region_export(Document& document, const RegionExportOptions& options) + { + auto pathString = options.path.empty() ? std::string("in memory") : path::to_utf8(options.path); + if (options.path.empty() && !options.isMakeSpritesheet) + { + toast_log(Level::ERROR, TOAST_EXPORT_REGION_PATH_EMPTY); + return false; + } + + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, options.spritesheetId); + auto region = spritesheet ? child_id_get(*spritesheet, ElementType::REGION, options.regionId) : nullptr; + auto texture = document.texture_get(options.spritesheetId); + std::vector pixels{}; + ivec2 exportSize{}; + if (!region || !texture || !texture->is_valid() || !region_pixels_get(*region, *texture, pixels, exportSize)) + { + toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, region ? region->name : std::string(), pathString); + return false; + } + + auto sourceRegion = *region; + auto outputPath = options.path; + if (!outputPath.empty()) + { + outputPath = window_asset_path_get(document, outputPath.replace_extension(PNG_EXTENSION)); + 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())) + { + toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, sourceRegion.name, pathString); + return false; + } + } + + if (options.isMakeSpritesheet || options.isRemoveCurrent) + { + document.snapshots.anm2_textures_push(localize.get(EDIT_EXPORT_REGION)); + + if (options.isMakeSpritesheet) + { + auto spritesheets = document.anm2.element_get(ElementType::SPRITESHEETS); + auto exported = element_make(ElementType::SPRITESHEET); + exported.id = element_child_next_id_get(*spritesheets, ElementType::SPRITESHEET); + exported.path = outputPath; + + auto exportedRegion = sourceRegion; + exportedRegion.id = 0; + exportedRegion.crop = {}; + exportedRegion.size = vec2(exportSize); + region_pivot_apply(exportedRegion); + 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}; + if (!outputPath.empty()) + document.spritesheet_hash_set_saved(exported.id); + else + document.spritesheetSaveHashes[exported.id] = 0; + } + + if (options.isRemoveCurrent) + { + if (auto source = document.anm2.element_get(ElementType::SPRITESHEET, options.spritesheetId)) + element_child_id_erase(*source, 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); + } + + toast_log(Level::INFO, TOAST_EXPORT_REGION, sourceRegion.name, pathString); + return true; + } + + bool region_drag_drop_update(Window& window, Manager& manager, Document& document, const Element& region, int index) + { + auto& selection = document.region.selection; + if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) + { + window.dragSelection = selection.contains(region.id) ? std::vector(selection.begin(), selection.end()) + : std::vector{region.id}; + ImGui::SetDragDropPayload(REGION_DRAG_DROP, window.dragSelection.data(), + window.dragSelection.size() * sizeof(int)); + ImGui::EndDragDropSource(); + } + + if (!ImGui::BeginDragDropTarget()) return false; + auto isMoved = false; + if (auto payload = ImGui::AcceptDragDropPayload(REGION_DRAG_DROP, ImGuiDragDropFlags_AcceptBeforeDelivery | + ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + { + auto cardMin = ImGui::GetWindowPos(); + auto cardMax = ImVec2(cardMin.x + ImGui::GetWindowSize().x, cardMin.y + ImGui::GetWindowSize().y); + auto isAfter = is_drop_after(cardMin, cardMax); + drop_line_draw(ImGui::GetForegroundDrawList(), cardMin, cardMax, isAfter); + + std::vector indices{}; + auto payloadIds = (const int*)payload->Data; + for (int i = 0; i < payload->DataSize / (int)sizeof(int); i++) + if (auto orderIndex = vector::find_index(window.order, payloadIds[i]); orderIndex != -1) + indices.push_back(orderIndex); + + if (!indices.empty() && payload->IsDelivery()) + { + std::sort(indices.begin(), indices.end()); + manager.command_push( + {manager.selected, + [&window, indices, movedIds = window.dragSelection, targetIndex = index + (isAfter ? 1 : 0), + spritesheetId = document.spritesheet.reference](Manager&, Document& document) mutable + { + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, spritesheetId); + if (!spritesheet) return; + window_edit(document, window.changeType, localize.get(EDIT_MOVE_REGIONS), + [&]() + { + vector::move_indices_to_position(spritesheet->children, indices, targetIndex); + document.region.selection = std::set(movedIds.begin(), movedIds.end()); + }); + }}); + isMoved = true; + } + } + ImGui::EndDragDropTarget(); + return isMoved; + } + + void region_drag_tooltip_update(Window& window, Document& document) + { + auto payload = ImGui::GetDragDropPayload(); + auto spritesheet = region_spritesheet_get(document); + if (!spritesheet || !payload || !payload->IsDataType(REGION_DRAG_DROP) || payload->IsDelivery() || + window.dragSelection.empty()) + return; + + if (payload->DataFrameCount != ImGui::GetFrameCount() && + ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceExtern | DRAG_DROP_SOURCE_FLAGS)) + { + ImGui::SetDragDropPayload(REGION_DRAG_DROP, window.dragSelection.data(), + window.dragSelection.size() * sizeof(int)); + ImGui::EndDragDropSource(); + } + + auto mousePos = ImGui::GetIO().MousePos; + ImGui::SetNextWindowPos(ImVec2(mousePos.x + DRAG_TOOLTIP_OFFSET.x, mousePos.y + DRAG_TOOLTIP_OFFSET.y)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); + if (ImGui::BeginTooltip()) + { + for (auto regionId : window.dragSelection) + if (auto region = child_id_get(*spritesheet, ElementType::REGION, regionId)) + ImGui::TextUnformatted(region->name.c_str()); + ImGui::EndTooltip(); + } + ImGui::PopStyleVar(2); + } + + void region_properties_popup_update(Window& window, Manager& manager, Document& document) + { + auto& reference = document.region.reference; + auto spritesheet = region_spritesheet_get(document); + auto target = spritesheet && reference != -1 ? child_id_get(*spritesheet, ElementType::REGION, reference) : nullptr; + + window.popup.trigger(); + if (ImGui::BeginPopupModal(window.popup.label(), &window.popup.isOpen, ImGuiWindowFlags_NoResize)) + { + if (!spritesheet || (reference != -1 && !target)) window.popup.close(); + + if (window.popup.isJustOpened && !window.isPreserveEditElementOnOpen) + window.editElement = target ? *target : element_make(ElementType::REGION); + if (window.popup.isJustOpened) window.isPreserveEditElementOnOpen = false; + auto& region = window.editElement; + + if (ImGui::BeginChild("##Child", child_size_get(REGION_POPUP_ROWS), ImGuiChildFlags_Borders)) + { + if (window.popup.isJustOpened) ImGui::SetKeyboardFocusHere(); + input_text_string(localize.get(BASIC_NAME), ®ion.name); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); + ImGui::DragFloat2(localize.get(BASIC_CROP), value_ptr(region.crop), DRAG_SPEED, 0.0f, 0.0f, + math::vec2_format_get(region.crop)); + ImGui::DragFloat2(localize.get(BASIC_SIZE), value_ptr(region.size), DRAG_SPEED, 0.0f, 0.0f, + math::vec2_format_get(region.size)); + ImGui::BeginDisabled(region.origin != Origin::CUSTOM); + ImGui::DragFloat2(localize.get(BASIC_PIVOT), value_ptr(region.pivot), DRAG_SPEED, 0.0f, 0.0f, + math::vec2_format_get(region.pivot)); + ImGui::EndDisabled(); + + const char* originOptions[std::size(ORIGIN_COMBO_ORDER)]{}; + for (int i = 0; i < (int)std::size(ORIGIN_COMBO_ORDER); ++i) + originOptions[i] = localize.get(ORIGIN_LABELS[(int)ORIGIN_COMBO_ORDER[i]]); + auto originIndex = (int)(std::ranges::find(ORIGIN_COMBO_ORDER, region.origin) - std::begin(ORIGIN_COMBO_ORDER)); + if (ImGui::Combo(localize.get(LABEL_REGION_PROPERTIES_ORIGIN), &originIndex, originOptions, + (int)std::size(originOptions))) + region.origin = ORIGIN_COMBO_ORDER[originIndex]; + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REGION_PROPERTIES_ORIGIN)); + region_pivot_apply(region); + } + ImGui::EndChild(); + + auto result = window_popup_buttons_draw(manager, localize.get(reference == -1 ? BASIC_ADD : BASIC_CONFIRM)); + if (result == PopupButton::CONFIRM) window_element_apply_push(window, manager, region, reference); + if (result != PopupButton::NONE) window.popup.close(); + ImGui::EndPopup(); + } + window.popup.end(); + } + + void region_export_popup_update(Window& window, Manager& manager, Settings& settings, Resources& resources, + Document& document) + { + auto spritesheet = region_spritesheet_get(document); + auto regionId = window.editId != -1 ? window.editId : document.region.reference; + auto region = spritesheet && regionId != -1 ? child_id_get(*spritesheet, ElementType::REGION, regionId) : nullptr; + + window.popup2.trigger(); + if (ImGui::BeginPopupModal(window.popup2.label(), &window.popup2.isOpen, ImGuiWindowFlags_NoResize)) + { + if (!region) window.popup2.close(); + if (region && window.popup2.isJustOpened) + { + auto filename = path::from_utf8(region->name).filename(); + settings.exportRegionPath = + settings.exportRegionPath.parent_path() / + (filename.empty() ? std::filesystem::path(REGION_EXPORT_NAME_DEFAULT) : filename).concat(PNG_EXTENSION); + } + if (window.dialog && window.dialog->is_selected(Dialog::REGION_EXPORT_PATH_SET)) + { + settings.exportRegionPath = window.dialog->path; + window.dialog->reset(); + } + + if (ImGui::BeginChild("##Export Region Child", child_size_get(REGION_POPUP_ROWS), 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 texture = document.texture_get(document.spritesheet.reference); + auto isValid = region && texture && texture->is_valid() && !texture->pixels.empty() && + (settings.isExportRegionMakeSpritesheet || !settings.exportRegionPath.empty()); + auto result = window_popup_buttons_draw(manager, localize.get(BASIC_CONFIRM), isValid); + if (result == PopupButton::CONFIRM) + { + if (!settings.exportRegionPath.empty()) settings.exportRegionPath.replace_extension(PNG_EXTENSION); + RegionExportOptions options{.spritesheetId = document.spritesheet.reference, + .regionId = regionId, + .path = settings.exportRegionPath, + .isMakeSpritesheet = settings.isExportRegionMakeSpritesheet, + .isRemoveCurrent = settings.isExportRegionRemoveCurrent}; + manager.command_push({manager.selected, [&window, options](Manager&, Document& document) + { + if (region_export(document, options) && options.isMakeSpritesheet) + window.newElementId = document.region.reference; + }}); + } + if (result != PopupButton::NONE) + { + window.editId = -1; + window.popup2.close(); + } + ImGui::EndPopup(); + } + window.popup2.end(); + } + + Window regions_window_register() + { + Window window{}; + window.title = LABEL_REGIONS_WINDOW; + window.isOpen = &Settings::windowIsRegions; + window.changeType = Document::SPRITESHEETS; + window.elementType = ElementType::REGION; + window.childLabel = "##Regions Child"; + window.cardLines = REGION_CARD_LINES; + window.unavailableText = TEXT_SELECT_SPRITESHEET; + window.addEdit = EDIT_ADD_REGION; + window.propertiesEdit = EDIT_SET_REGION_PROPERTIES; + window.flags = WINDOW_PROPERTIES | WINDOW_ADD | WINDOW_REMOVE_UNUSED | WINDOW_TRIM | WINDOW_EXPORT | WINDOW_COPY | + WINDOW_PASTE; + window.footer = {{WINDOW_ADD, WINDOW_EXPORT, WINDOW_REMOVE_UNUSED}}; + window.tooltips = {{WINDOW_ADD, TOOLTIP_ADD_REGION}, + {WINDOW_REMOVE_UNUSED, TOOLTIP_REMOVE_UNUSED_REGIONS}, + {WINDOW_TRIM, TOOLTIP_TRIM_REGIONS}}; + 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.container_get = region_spritesheet_get; + window.insert_index_get = region_insert_index_get; + window.is_available = [](Window&, Document& document) { return region_spritesheet_get(document) != nullptr; }; + window.card_image_get = region_image_get; + window.row_drag_drop_update = region_drag_drop_update; + window.row_select = [](Window&, Document& document, int) + { + document.editTarget = Document::EditTarget::REGION; + document.reference = {document.reference.animationIndex}; + document.frames.reference = -1; + document.frames.selection.clear(); + }; + window.tooltip_draw = [](Document& document, Resources& resources, const Element& region) + { + window_tooltip_image_draw( + region_image_get(document, resources, region), + [&]() + { + window_tooltip_name_draw(resources, region.name); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_CROP), std::make_format_args(region.crop.x, region.crop.y)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_SIZE), std::make_format_args(region.size.x, region.size.y)).c_str()); + auto originLabel = localize.get(ORIGIN_LABELS[(int)region.origin]); + ImGui::TextUnformatted( + (region.origin == Origin::CUSTOM + ? std::vformat(localize.get(FORMAT_PIVOT), std::make_format_args(region.pivot.x, region.pivot.y)) + : std::vformat(localize.get(FORMAT_ORIGIN), std::make_format_args(originLabel))) + .c_str()); + }); + }; + window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + document.region.reference = -1; + window.editElement = element_make(ElementType::REGION); + window.popup.open(); + }; + window.properties = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto& selection = document.region.selection; + if (selection.size() != 1 || !window_element_get(window, document, *selection.begin())) return; + document.region.reference = *selection.begin(); + window.popup.open(); + }; + window.export_open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + window.editId = *document.region.selection.begin(); + window.popup2.open(); + }; + window.remove_unused = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto spritesheetId = document.spritesheet.reference; + auto unused = document.anm2.region_unused(spritesheetId); + auto spritesheet = region_spritesheet_get(document); + if (unused.empty() || !spritesheet) return; + window_edit(document, window.changeType, localize.get(EDIT_REMOVE_UNUSED_REGIONS), + [&]() + { + animations_tracks_each(document.anm2.root, ElementType::LAYER_ANIMATION, + [&](Element& track) + { + auto layer = + document.anm2.element_get(ElementType::LAYER_ELEMENT, track.layerId); + if (!layer || layer->spritesheetId != spritesheetId) return; + for (auto& frame : track.children) + if (frame.type == ElementType::FRAME && unused.contains(frame.regionId)) + frame.regionId = -1; + }); + for (auto id : unused) + element_child_id_erase(*spritesheet, ElementType::REGION, id); + }); + }; + window.trim = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto& region = document.region; + window_edit(document, window.changeType, localize.get(EDIT_TRIM_REGIONS), + [&]() + { + if (!document.regions_trim(document.spritesheet.reference, region.selection)) return; + if (region.reference != -1 && !region.selection.contains(region.reference)) + region.reference = *region.selection.begin(); + document.reference = {document.reference.animationIndex}; + document.frames.reference = -1; + document.frames.selection.clear(); + }); + }; + window.paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) + { + auto spritesheetId = document.spritesheet.reference; + auto spritesheet = region_spritesheet_get(document); + if (!spritesheet || clipboard.is_empty()) return; + + auto maxIdBefore = element_child_max_id_get(*spritesheet, ElementType::REGION); + auto insertIndex = region_insert_index_get(document); + auto pasted = document.anm2; + std::string errorString{}; + if (!pasted.deserialize(ElementType::REGION, clipboard.get(), true, &errorString, {}, spritesheetId)) + { + toast_log(Level::ERROR, TOAST_DESERIALIZE_REGIONS_FAILED, errorString); + return; + } + + window_edit(document, window.changeType, localize.get(EDIT_PASTE_REGIONS), + [&]() + { + document.anm2 = std::move(pasted); + auto target = region_spritesheet_get(document); + auto maxIdAfter = element_child_max_id_get(*target, ElementType::REGION); + if (maxIdAfter <= maxIdBefore) return; + std::vector pastedIndices{}; + for (int i = 0; i < (int)target->children.size(); i++) + if (target->children[i].type == ElementType::REGION && target->children[i].id > maxIdBefore) + pastedIndices.push_back(i); + vector::move_indices_to_position(target->children, pastedIndices, insertIndex); + window.newElementId = maxIdAfter; + document.region.selection = {maxIdAfter}; + document.region.reference = maxIdAfter; + }); + }; + window.rows_update = [](Window& window, Manager& manager, Settings& settings, Resources& resources, + Clipboard& clipboard, Document& document) + { + window_cards_draw(window, manager, settings, resources, clipboard, document, region_spritesheet_get(document)); + region_drag_tooltip_update(window, document); + }; + window.popup_update = + [](Window& window, Manager& manager, Settings& settings, Resources& resources, Clipboard&, Document& document) + { + if (manager.isMakeRegionRequested) + { + document.spritesheet.reference = manager.makeRegionSpritesheetId; + document.region.reference = -1; + window.editElement = manager.makeRegion; + window.isPreserveEditElementOnOpen = true; + window.popup.open(); + manager.isMakeRegionRequested = false; + } + region_properties_popup_update(window, manager, document); + region_export_popup_update(window, manager, settings, resources, document); + }; + return window; + } +} diff --git a/src/imgui/window/sounds.cpp b/src/imgui/window/sounds.cpp new file mode 100644 index 0000000..ad6ee9d --- /dev/null +++ b/src/imgui/window/sounds.cpp @@ -0,0 +1,131 @@ +#include "window.hpp" + +#include + +#include "path.hpp" +#include "toast.hpp" + +using namespace anm2ed::resource; +using namespace anm2ed::types; +using namespace anm2ed::util; + +namespace anm2ed::imgui +{ + constexpr int SOUND_CARD_LINES = 2; + + Window sounds_window_register() + { + Window window{}; + window.title = LABEL_SOUNDS_WINDOW; + window.isOpen = &Settings::windowIsSounds; + window.changeType = Document::SOUNDS; + window.containerType = ElementType::SOUNDS; + window.elementType = ElementType::SOUND_ELEMENT; + window.childLabel = "##Sounds Child"; + window.cardLines = SOUND_CARD_LINES; + window.pasteEdit = TOAST_SOUNDS_PASTE; + window.removeUnusedEdit = EDIT_REMOVE_UNUSED_SOUNDS; + window.deserializeFailedToast = TOAST_SOUNDS_DESERIALIZE_ERROR; + window.flags = WINDOW_PLAY | WINDOW_OPEN_DIRECTORY | WINDOW_ADD | WINDOW_REMOVE_UNUSED | WINDOW_RELOAD | + WINDOW_REPLACE | WINDOW_COPY | WINDOW_PASTE; + window.footer = {{WINDOW_ADD, WINDOW_REMOVE_UNUSED, WINDOW_RELOAD, WINDOW_REPLACE}}; + window.tooltips = {{WINDOW_ADD, TOOLTIP_SOUND_ADD}, + {WINDOW_REMOVE_UNUSED, TOOLTIP_REMOVE_UNUSED_SOUNDS}, + {WINDOW_RELOAD, TOOLTIP_RELOAD_SOUNDS}, + {WINDOW_REPLACE, TOOLTIP_REPLACE_SOUND}}; + window.storage_get = [](Document& document) -> Storage& { return document.sound; }; + window.row_label_get = [](Document&, const Element& sound) + { + auto pathString = path::to_utf8(sound.path); + return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(sound.id, pathString)); + }; + window.row_select = [](Window&, Document& document, int id) + { + if (auto audio = document.sound_get(id); audio && ImGui::IsItemClicked(ImGuiMouseButton_Left)) audio->play(); + }; + window.card_image_get = [](Document& document, Resources& resources, const Element& sound) + { + auto audio = document.sound_get(sound.id); + auto isValid = audio && audio->is_valid(); + auto& texture = resources.icons[isValid ? icon::SOUND : icon::NONE]; + return WindowCardImage{.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid}; + }; + window.tooltip_draw = [](Document& document, Resources& resources, const Element& sound) + { + auto audio = document.sound_get(sound.id); + window_tooltip_name_draw(resources, path::to_utf8(sound.path)); + ImGui::Text("%s: %d", localize.get(BASIC_ID), sound.id); + if (audio && audio->is_valid()) + ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); + else + { + ImGui::Spacing(); + ImGui::TextWrapped("%s", localize.get(TOOLTIP_SOUND_INVALID)); + } + }; + window.add = [](Window& window, Manager&, Settings&, Document&, Clipboard&) + { + if (window.dialog) window.dialog->file_open(Dialog::SOUND_OPEN, true); + }; + window.replace = [](Window& window, Manager&, Settings&, Document&, Clipboard&) + { + if (window.dialog) window.dialog->file_open(Dialog::SOUND_REPLACE); + }; + window.play = [](Window&, Manager&, Settings&, Document& document, Clipboard&) + { + if (auto audio = document.sound_get(*document.sound.selection.begin())) audio->play(); + }; + window.open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto sound = window_element_get(window, document, document.sound.reference); + if (sound && window.dialog) window_directory_open(*window.dialog, document, sound->path); + }; + window.reload = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + window_edit(document, window.changeType, localize.get(EDIT_RELOAD_SOUNDS), + [&]() + { + for (auto id : document.sound.selection) + if (auto sound = window_element_get(window, document, id)) + { + document.sound_reload(id); + toast_log(Level::INFO, TOAST_RELOAD_SOUND, id, path::to_utf8(sound->path)); + } + }); + }; + window.body_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) + { + if (!window.dialog) return; + if (window.dialog->is_selected(Dialog::SOUND_OPEN)) + { + manager.command_push({manager.selected, [&window, paths = window.dialog->paths](Manager&, Document& document) + { + document.sounds_add(paths); + window.newElementId = document.sound.reference; + }}); + window.dialog->reset(); + } + + if (window.dialog->is_selected(Dialog::SOUND_REPLACE)) + { + if (document.sound.selection.size() == 1 && !window.dialog->path.empty()) + manager.command_push({manager.selected, [&window, id = *document.sound.selection.begin(), + dialogPath = window.dialog->path](Manager&, Document& document) + { + auto sound = window_element_get(window, document, id); + if (!sound) return; + window_edit(document, window.changeType, localize.get(EDIT_REPLACE_SOUND), + [&]() + { + sound->path = window_asset_path_get(document, dialogPath); + document.sound_reload(id); + toast_log(Level::INFO, TOAST_REPLACE_SOUND, id, + path::to_utf8(sound->path)); + }); + }}); + window.dialog->reset(); + } + }; + return window; + } +} diff --git a/src/imgui/window/spritesheets.cpp b/src/imgui/window/spritesheets.cpp new file mode 100644 index 0000000..78174ee --- /dev/null +++ b/src/imgui/window/spritesheets.cpp @@ -0,0 +1,368 @@ +#include "window.hpp" + +#include + +#include "path.hpp" +#include "toast.hpp" +#include "util/imgui/input.hpp" +#include "util/imgui/layout.hpp" +#include "working_directory.hpp" + +using namespace anm2ed::resource; +using namespace anm2ed::types; +using namespace anm2ed::util; + +namespace anm2ed::imgui +{ + constexpr int SPRITESHEET_CARD_LINES = 4; + constexpr int MERGE_OPTIONS_ROWS = 6; + constexpr int PADDING_MAX = 100; + + bool is_spritesheet_regions(Document& document, int id) + { + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); + return spritesheet && child_first_get(*spritesheet, ElementType::REGION); + } + + void spritesheets_save(Document& document, const std::set& ids) + { + for (auto id : ids) + { + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); + auto texture = document.texture_get(id); + if (!spritesheet || !texture) continue; + auto pathString = path::to_utf8(spritesheet->path); + WorkingDirectory workingDirectory(document.directory_get()); + path::ensure_directory(spritesheet->path.parent_path()); + auto isSaved = texture->write_png(spritesheet->path); + if (isSaved) document.spritesheet_hash_set_saved(id); + toast_log(isSaved ? Level::INFO : Level::ERROR, isSaved ? TOAST_SAVE_SPRITESHEET : TOAST_SAVE_SPRITESHEET_FAILED, + id, pathString); + } + } + + void spritesheet_path_change(Window& window, Manager& manager, int id, const std::filesystem::path& dialogPath, + StringType edit, bool isWritten) + { + manager.command_push({manager.selected, [&window, id, dialogPath, edit, isWritten](Manager&, Document& document) + { + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); + auto texture = document.texture_get(id); + if (!spritesheet || (isWritten && !texture)) return; + window_edit(document, window.changeType, localize.get(edit), + [&]() + { + auto newPath = window_asset_path_get(document, dialogPath); + auto pathString = path::to_utf8(newPath); + if (isWritten) + { + WorkingDirectory workingDirectory(document.directory_get()); + path::ensure_directory(newPath.parent_path()); + if (!texture->write_png(newPath)) + { + toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); + return; + } + } + spritesheet->path = newPath; + if (isWritten) + document.texturePaths[id] = newPath; + else + document.texture_reload(id); + document.spritesheet_hash_set_saved(id); + toast_log(Level::INFO, + isWritten ? TOAST_SAVE_SPRITESHEET : TOAST_REPLACE_SPRITESHEET, id, + pathString); + }); + }}); + } + + void spritesheet_textures_edit(Document& document, StringType edit, Document::ChangeType changeType, + const std::function& behavior, StringType successToast, StringType failToast) + { + document.snapshots.anm2_textures_push(localize.get(edit)); + auto isSuccess = behavior(); + toast_log(isSuccess ? Level::INFO : Level::ERROR, isSuccess ? successToast : failToast); + document.change(changeType); + } + + Window spritesheets_window_register() + { + Window window{}; + window.title = LABEL_SPRITESHEETS_WINDOW; + window.isOpen = &Settings::windowIsSpritesheets; + window.changeType = Document::SPRITESHEETS; + window.containerType = ElementType::SPRITESHEETS; + window.elementType = ElementType::SPRITESHEET; + window.childLabel = "##Spritesheets Child"; + window.cardLines = SPRITESHEET_CARD_LINES; + window.pasteEdit = EDIT_PASTE_SPRITESHEETS; + window.deserializeFailedToast = TOAST_DESERIALIZE_SPRITESHEETS_FAILED; + window.flags = WINDOW_OPEN_DIRECTORY | WINDOW_SET_FILE_PATH | WINDOW_ADD | WINDOW_REMOVE_UNUSED | WINDOW_RELOAD | + WINDOW_REPLACE | WINDOW_MERGE | WINDOW_PACK | WINDOW_SAVE | WINDOW_COPY | WINDOW_PASTE; + window.footer = {{WINDOW_ADD, WINDOW_RELOAD, WINDOW_REPLACE}, {WINDOW_REMOVE_UNUSED, WINDOW_SAVE}}; + window.tooltips = { + {WINDOW_ADD, TOOLTIP_ADD_SPRITESHEET}, {WINDOW_RELOAD, TOOLTIP_RELOAD_SPRITESHEETS}, + {WINDOW_REPLACE, TOOLTIP_REPLACE_SPRITESHEET}, {WINDOW_REMOVE_UNUSED, TOOLTIP_REMOVE_UNUSED_SPRITESHEETS}, + {WINDOW_PACK, TOOLTIP_PACK_SPRITESHEET}, {WINDOW_SAVE, TOOLTIP_SAVE_SPRITESHEETS}}; + window.enabled = {{WINDOW_PACK, [](Window&, Document& document) + { + auto& selection = document.spritesheet.selection; + return selection.size() == 1 && is_spritesheet_regions(document, *selection.begin()); + }}}; + window.popup = PopupHelper(LABEL_SPRITESHEETS_MERGE_POPUP, POPUP_SMALL_NO_HEIGHT); + window.popup2 = PopupHelper(LABEL_SPRITESHEETS_PACK_POPUP, POPUP_SMALL_NO_HEIGHT); + window.popup3 = PopupHelper(LABEL_TASKBAR_OVERWRITE_FILE, POPUP_SMALL_NO_HEIGHT); + window.storage_get = [](Document& document) -> Storage& { return document.spritesheet; }; + window.row_label_get = [](Document& document, const Element& spritesheet) + { + auto pathString = path::to_utf8(spritesheet.path); + auto label = std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(spritesheet.id, pathString)); + return document.spritesheet_is_dirty(spritesheet.id) + ? std::vformat(localize.get(FORMAT_SPRITESHEET_NOT_SAVED), std::make_format_args(label)) + : label; + }; + window.row_select = [](Window&, Document& document, int) + { + document.editTarget = Document::EditTarget::SPRITESHEET; + document.region.reference = -1; + document.region.selection.clear(); + }; + window.card_image_get = [](Document& document, Resources& resources, const Element& spritesheet) + { + auto texture = document.texture_get(spritesheet.id); + auto isValid = texture && texture->is_valid(); + auto& image = isValid ? *texture : resources.icons[icon::NONE]; + return WindowCardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}; + }; + window.tooltip_draw = [](Document& document, Resources& resources, const Element& spritesheet) + { + auto texture = document.texture_get(spritesheet.id); + auto isValid = texture && texture->is_valid(); + auto& image = isValid ? *texture : resources.icons[icon::NONE]; + window_tooltip_image_draw( + {.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}, + [&]() + { + window_tooltip_name_draw(resources, path::to_utf8(spritesheet.path)); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_ID), std::make_format_args(spritesheet.id)).c_str()); + if (isValid) + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_TEXTURE_SIZE), std::make_format_args(image.size.x, image.size.y)) + .c_str()); + else + ImGui::TextUnformatted(localize.get(TOOLTIP_SPRITESHEET_INVALID)); + ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); + }); + }; + window.add = [](Window& window, Manager&, Settings&, Document&, Clipboard&) + { + if (window.dialog) window.dialog->file_open(Dialog::SPRITESHEET_OPEN, true); + }; + window.replace = [](Window& window, Manager&, Settings&, Document&, Clipboard&) + { + if (window.dialog) window.dialog->file_open(Dialog::SPRITESHEET_REPLACE); + }; + window.path_set = [](Window& window, Manager&, Settings&, Document&, Clipboard&) + { + if (window.dialog) window.dialog->file_save(Dialog::SPRITESHEET_PATH_SET); + }; + window.open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto spritesheet = window_element_get(window, document, document.spritesheet.reference); + if (spritesheet && window.dialog) window_directory_open(*window.dialog, document, spritesheet->path); + }; + window.remove_unused = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto unused = document.anm2.element_unused(ElementType::SPRITESHEET); + auto spritesheets = window_container_get(window, document); + if (unused.empty() || !spritesheets) return; + window_edit(document, window.changeType, localize.get(EDIT_REMOVE_UNUSED_SPRITESHEETS), + [&]() + { + for (auto id : unused) + if (auto spritesheet = window_element_get(window, document, id)) + { + toast_log(Level::INFO, TOAST_REMOVE_SPRITESHEET, id, path::to_utf8(spritesheet->path)); + element_child_id_erase(*spritesheets, ElementType::SPRITESHEET, id); + } + }); + }; + window.reload = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto selected = document.spritesheet.selection; + window_edit(document, window.changeType, localize.get(EDIT_RELOAD_SPRITESHEETS), + [&]() + { + for (auto id : selected) + document.texture_reload(id); + }); + for (auto id : selected) + if (auto spritesheet = window_element_get(window, document, id)) + { + document.spritesheet_hash_set_saved(id); + toast_log(Level::INFO, TOAST_RELOAD_SPRITESHEET, id, path::to_utf8(spritesheet->path)); + } + }; + window.save = [](Window& window, Manager&, Settings& settings, Document& document, Clipboard&) + { + if (!settings.fileIsWarnOverwrite) return spritesheets_save(document, document.spritesheet.selection); + window.selection2 = document.spritesheet.selection; + window.popup3.open(); + }; + window.merge_open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + window.selection = document.spritesheet.selection; + window.popup.open(); + }; + window.pack_open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + window.editId = *document.spritesheet.selection.begin(); + window.popup2.open(); + }; + window.body_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) + { + if (!window.dialog) return; + auto& selection = document.spritesheet.selection; + if (window.dialog->is_selected(Dialog::SPRITESHEET_OPEN)) + { + manager.command_push({manager.selected, [&window, paths = window.dialog->paths](Manager&, Document& document) + { + document.spritesheets_add(paths); + document.region.reference = -1; + document.region.selection.clear(); + window.newElementId = document.spritesheet.reference; + }}); + window.dialog->reset(); + } + + for (auto [type, edit] : {std::pair{Dialog::SPRITESHEET_REPLACE, EDIT_REPLACE_SPRITESHEET}, + std::pair{Dialog::SPRITESHEET_PATH_SET, EDIT_SET_SPRITESHEET_FILE_PATH}}) + { + if (!window.dialog->is_selected(type)) continue; + if (selection.size() == 1 && !window.dialog->path.empty()) + spritesheet_path_change(window, manager, *selection.begin(), window.dialog->path, edit, + type == Dialog::SPRITESHEET_PATH_SET); + window.dialog->reset(); + } + }; + window.popup_update = + [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard&, Document& document) + { + window.popup.trigger(); + if (ImGui::BeginPopupModal(window.popup.label(), &window.popup.isOpen, ImGuiWindowFlags_NoResize)) + { + settings.mergeSpritesheetsRegionOrigin = + glm::clamp(settings.mergeSpritesheetsRegionOrigin, (int)origin::TOP_LEFT, (int)origin::ORIGIN_CENTER); + + if (ImGui::BeginChild("##Merge Spritesheets Options", child_size_get(MERGE_OPTIONS_ROWS), + ImGuiChildFlags_Borders)) + { + ImGui::SeparatorText(localize.get(LABEL_REGION_PROPERTIES_ORIGIN)); + ImGui::RadioButton(localize.get(LABEL_MERGE_SPRITESHEETS_APPEND_BOTTOM), &settings.mergeSpritesheetsOrigin, + APPEND_BOTTOM); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_SPRITESHEETS_BOTTOM_LEFT)); + ImGui::SameLine(); + ImGui::RadioButton(localize.get(LABEL_MERGE_SPRITESHEETS_APPEND_RIGHT), &settings.mergeSpritesheetsOrigin, + APPEND_RIGHT); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_SPRITESHEETS_TOP_RIGHT)); + + ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); + ImGui::Checkbox(localize.get(LABEL_MERGE_MAKE_SPRITESHEET_REGIONS), &settings.mergeSpritesheetsIsMakeRegions); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_MAKE_SPRITESHEET_REGIONS)); + + ImGui::BeginDisabled(!settings.mergeSpritesheetsIsMakeRegions); + ImGui::Checkbox(localize.get(LABEL_MERGE_MAKE_PRIMARY_SPRITESHEET_REGION), + &settings.mergeSpritesheetsIsMakePrimaryRegion); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_MAKE_PRIMARY_SPRITESHEET_REGION)); + const char* regionOriginOptions[] = {localize.get(LABEL_REGION_ORIGIN_TOP_LEFT), + localize.get(LABEL_REGION_ORIGIN_CENTER)}; + ImGui::Combo(localize.get(LABEL_REGION_PROPERTIES_ORIGIN), &settings.mergeSpritesheetsRegionOrigin, + regionOriginOptions, IM_ARRAYSIZE(regionOriginOptions)); + ImGui::EndDisabled(); + } + ImGui::EndChild(); + + auto result = + window_popup_buttons_draw(manager, localize.get(BASIC_MERGE), window.selection.size() > 1, BASIC_CANCEL); + if (result == PopupButton::CONFIRM) + manager.command_push( + {manager.selected, + [ids = window.selection, isAppendRight = settings.mergeSpritesheetsOrigin == APPEND_RIGHT, + isMakeRegions = settings.mergeSpritesheetsIsMakeRegions, + isMakePrimaryRegion = settings.mergeSpritesheetsIsMakePrimaryRegion, + regionOrigin = (origin::Type)settings.mergeSpritesheetsRegionOrigin](Manager&, Document& document) + { + spritesheet_textures_edit( + document, EDIT_MERGE_SPRITESHEETS, Document::ALL, + [&]() + { + if (!document.spritesheets_merge(ids, isAppendRight, isMakeRegions, isMakePrimaryRegion, + regionOrigin)) + return false; + document.spritesheet.selection = {*ids.begin()}; + document.spritesheet.reference = *ids.begin(); + document.region.reference = -1; + document.region.selection.clear(); + return true; + }, + TOAST_MERGE_SPRITESHEETS, TOAST_MERGE_SPRITESHEETS_FAILED); + }}); + if (result != PopupButton::NONE) + { + window.selection.clear(); + window.popup.close(); + } + ImGui::EndPopup(); + } + window.popup.end(); + + window.popup2.trigger(); + if (ImGui::BeginPopupModal(window.popup2.label(), &window.popup2.isOpen, ImGuiWindowFlags_NoResize)) + { + settings.packPadding = std::max(0, settings.packPadding); + if (ImGui::BeginChild("##Pack Spritesheet Options", child_size_get(), ImGuiChildFlags_Borders)) + ImGui::DragInt(localize.get(LABEL_PACK_PADDING), &settings.packPadding, DRAG_SPEED, 0, PADDING_MAX); + ImGui::EndChild(); + + auto result = window_popup_buttons_draw(manager, localize.get(BASIC_PACK), + is_spritesheet_regions(document, window.editId), BASIC_CANCEL); + if (result == PopupButton::CONFIRM) + manager.command_push({manager.selected, + [id = window.editId, padding = settings.packPadding](Manager&, Document& document) + { + spritesheet_textures_edit( + document, EDIT_PACK_SPRITESHEET, Document::SPRITESHEETS, + [&]() { return document.spritesheet_pack(id, padding); }, TOAST_PACK_SPRITESHEET, + TOAST_PACK_SPRITESHEET_FAILED); + }}); + if (result != PopupButton::NONE) + { + window.editId = -1; + window.popup2.close(); + } + ImGui::EndPopup(); + } + window.popup2.end(); + + window.popup3.trigger(); + if (ImGui::BeginPopupModal(window.popup3.label(), &window.popup3.isOpen, ImGuiWindowFlags_NoResize)) + { + ImGui::TextUnformatted(localize.get(LABEL_OVERWRITE_CONFIRMATION)); + auto result = window_popup_buttons_draw(manager, localize.get(BASIC_YES), true, BASIC_NO); + if (result == PopupButton::CONFIRM) + manager.command_push({manager.selected, [ids = window.selection2](Manager&, Document& document) + { spritesheets_save(document, ids); }}); + if (result != PopupButton::NONE) + { + window.selection2.clear(); + window.popup3.close(); + } + ImGui::EndPopup(); + } + window.popup3.end(); + }; + return window; + } +} diff --git a/src/imgui/window/timeline/commands.cpp b/src/imgui/window/timeline/commands.cpp index d586cf1..3491e73 100644 --- a/src/imgui/window/timeline/commands.cpp +++ b/src/imgui/window/timeline/commands.cpp @@ -1880,16 +1880,7 @@ namespace anm2ed::imgui item_base_properties_open = [&](int type, int id) { - switch (type) - { - case LAYER: - manager.layer_properties_open(id); - break; - case NULL_: - manager.null_properties_open(id); - default: - break; - }; + if (auto row = anm2ed::track_container_get((ItemType)type)) manager.item_properties_open(row->element, id); }; group_properties_close = [&]() diff --git a/src/imgui/window/window.cpp b/src/imgui/window/window.cpp index 9ef6747..06e65f8 100644 --- a/src/imgui/window/window.cpp +++ b/src/imgui/window/window.cpp @@ -3,24 +3,13 @@ #include #include #include -#include -#include -#include #include "actions.hpp" -#include "log.hpp" -#include "math.hpp" #include "path.hpp" #include "strings.hpp" #include "toast.hpp" -#include "util/imgui/draw.hpp" -#include "util/imgui/input.hpp" #include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" -#include "util/imgui/tooltip.hpp" -#include "util/imgui/tree.hpp" -#include "vector.hpp" -#include "working_directory.hpp" using namespace anm2ed::resource; using namespace anm2ed::types; @@ -29,334 +18,572 @@ using namespace glm; 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; + constexpr float SCROLL_CENTER = 0.5f; + constexpr float TOOLTIP_PADDING_MULTIPLIER = 4.0f; + constexpr float PREVIEW_VIEWPORT_FRACTION = 0.5f; + constexpr const char* CONTEXT_MENU_LABEL = "##Context Menu"; + + struct WindowFlagInfo + { + WindowFlag flag; + ActionType action; + Window::Command Window::* command; + }; + + constexpr WindowFlagInfo WINDOW_FLAG_INFOS[] = { +#define X(symbol, action, command) {WINDOW_##symbol, action, &Window::command}, + WINDOW_FLAGS +#undef X + }; bool is_drag_drop_active() { return ImGui::GetDragDropPayload() != nullptr; } - enum class AnimationDropZone + Element* window_container_get(const Window& window, Document& document) { - BEFORE, - INSIDE, - AFTER - }; - - enum class AnimationDragDropType - { - ANIMATION, - GROUP - }; - - struct SpritesheetMergeOptions - { - bool isAppendRight{}; - bool isMakeRegions{}; - bool isMakePrimaryRegion{}; - origin::Type regionOrigin{}; - }; - - struct AnimationMergeOptions - { - std::set selection{}; - int reference{-1}; - merge::Type type{}; - 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; + return window.container_get ? window.container_get(document) : document.anm2.element_get(window.containerType); } - int window_element_count_get(const Window& window, const Element* container) + Element* window_element_get(const Window& window, Document& document, int key) { - int count{}; - if (!container) return count; - for (const auto& element : container->children) - if (element.type == window.elementType) ++count; - return count; - } - - Element* window_container_get(const Window& window, Anm2& anm2) { return anm2.element_get(window.containerType); } - - Element* window_element_get(const Window& window, Anm2& anm2, int key) - { - if (window.element_get) return window.element_get(anm2, key); - auto container = window_container_get(window, anm2); + if (window.element_get) return window.element_get(document.anm2, key); + auto container = window_container_get(window, document); return container ? child_id_get(*container, window.elementType, key) : nullptr; } - int region_insert_index_get(const Element& spritesheet, const Storage& storage) + void window_element_apply_push(Window& window, Manager& manager, const Element& edited, int reference) { - int index = (int)spritesheet.children.size(); - for (int i = 0; i < (int)spritesheet.children.size(); i++) - { - const auto& child = spritesheet.children[i]; - if (child.type != ElementType::REGION) continue; - if (storage.selection.contains(child.id) || (storage.selection.empty() && storage.reference == child.id)) - index = i + 1; - } - return index; + manager.command_push( + {manager.selected, [&window, edited, reference](Manager&, Document& document) + { + auto container = window_container_get(window, document); + auto target = + reference == -1 || !container ? nullptr : child_id_get(*container, window.elementType, reference); + if (!container || (reference != -1 && !target)) return; + window_edit( + document, window.changeType, localize.get(reference == -1 ? window.addEdit : window.propertiesEdit), + [&]() + { + auto changed = edited; + changed.type = window.elementType; + changed.tag = element_make(window.elementType).tag; + changed.id = reference == -1 ? element_child_next_id_get(*container, window.elementType) : reference; + if (target) + *target = changed; + else + { + auto insertIndex = + window.insert_index_get ? window.insert_index_get(document) : (int)container->children.size(); + container->children.insert(container->children.begin() + insertIndex, changed); + window.newElementId = changed.id; + } + auto& storage = window.storage_get(document); + storage.selection = {changed.id}; + storage.reference = changed.id; + if (window.row_select) window.row_select(window, document, changed.id); + }); + }}); } - int window_track_id_get(const Element& item, ElementType trackType) - { - return trackType == ElementType::LAYER_ANIMATION ? item.layerId : item.nullId; - } - - void window_track_shell_push(Element& destination, std::set& copiedTrackIds, const Element& source, - ElementType trackType, int groupId) - { - if (source.type != trackType) return; - auto trackId = window_track_id_get(source, trackType); - if (copiedTrackIds.contains(trackId)) return; - copiedTrackIds.insert(trackId); - - auto item = element_make(trackType); - item.layerId = source.layerId; - item.nullId = source.nullId; - item.groupId = source.groupId != -1 ? source.groupId : groupId; - item.isVisible = source.isVisible; - destination.children.push_back(item); - } - - void window_group_root_push(Element& group) - { - auto root = element_make(ElementType::ROOT_ANIMATION); - root.children.push_back(element_make(ElementType::FRAME)); - group.children.push_back(root); - } - - Element window_track_container_shell_copy(const Element* source, ElementType containerType, ElementType trackType) - { - auto destination = element_make(containerType); - if (!source) return destination; - - auto nextGroupId = element_child_next_id_get(*source, ElementType::GROUP); - std::set copiedTrackIds{}; - for (const auto& sourceItem : source->children) - { - if (sourceItem.type != ElementType::GROUP) - { - window_track_shell_push(destination, copiedTrackIds, sourceItem, trackType, -1); - continue; - } - - auto group = element_make(ElementType::GROUP); - group.id = sourceItem.id >= 0 ? sourceItem.id : nextGroupId++; - group.name = sourceItem.name; - group.isExpanded = sourceItem.isExpanded; - group.isVisible = sourceItem.isVisible; - window_group_root_push(group); - destination.children.push_back(group); - - for (const auto& child : sourceItem.children) - window_track_shell_push(destination, copiedTrackIds, child, trackType, group.id); - } - return destination; - } - - void window_edit(Window& window, Document& document, const std::string& message, auto behavior) - { - document.snapshots.anm2_push(message); - behavior(); - document.change(window.changeType); - } - - void window_edit(Document& document, Document::ChangeType changeType, const std::string& message, auto behavior) + void window_edit(Document& document, Document::ChangeType changeType, const std::string& message, + const std::function& behavior) { document.snapshots.anm2_push(message); behavior(); document.change(changeType); } - void window_rename_finish(Window& window, Manager& manager, int key, int count, const std::string& name) - { - auto changeType = window.changeType; - auto containerType = window.containerType; - auto elementType = window.elementType; - auto elementGet = window.element_get; - auto renameEdit = window.renameEdit; - auto renameFinish = window.rename_finish; - manager.command_push({manager.selected, [changeType, containerType, elementType, elementGet, renameEdit, - renameFinish, key, count, name](Manager&, Document& document) mutable - { - auto element = elementGet ? elementGet(document.anm2, key) : nullptr; - if (!element) - if (auto container = document.anm2.element_get(containerType)) - element = child_id_get(*container, elementType, key); - if (!element || element->name == name) return; - - document.snapshots.anm2_push(localize.get(renameEdit)); - element->name = name; - if (renameFinish) renameFinish(document, *element, key, count); - document.change(changeType); - }}); - } - void window_command_push(Window& window, Manager& manager, Settings& settings, Clipboard& clipboard, const Window::Command& command) { if (!command) return; - auto queuedCommand = command; manager.command_push({manager.selected, - [&window, &settings, &clipboard, queuedCommand](Manager& manager, Document& document) mutable - { queuedCommand(window, manager, settings, document, clipboard); }}); + [&window, &settings, &clipboard, command](Manager& manager, Document& document) mutable + { command(window, manager, settings, document, clipboard); }}); } - void window_copy(Window& window, Manager& manager, Settings& settings, Document& document, Clipboard& clipboard) + void window_rename_finish(Window& window, Manager& manager, int key, int count, const std::string& name) { - if (window.copy) - { - window_command_push(window, manager, settings, clipboard, window.copy); - return; - } - - auto& selection = window.storage_get(document).selection; - if (selection.empty()) return; + manager.command_push({manager.selected, [&window, key, count, name](Manager&, Document& document) + { + auto element = window_element_get(window, document, key); + if (!element || element->name == name) return; + window_edit(document, window.changeType, localize.get(window.renameEdit), + [&]() + { + element->name = name; + if (window.rename_finish) + window.rename_finish(document, *element, key, count); + }); + }}); + } + void window_copy(Window& window, Document& document, Clipboard& clipboard) + { std::string clipboardText{}; - for (auto key : selection) - if (auto element = window_element_get(window, document.anm2, key)) clipboardText += element_to_string(*element); - clipboard.set(clipboardText); + for (auto key : window.storage_get(document).selection) + if (auto element = window_element_get(window, document, key)) clipboardText += element_to_string(*element); + if (!clipboardText.empty()) clipboard.set(clipboardText); } - void window_paste(Window& window, Manager& manager, Settings& settings, Document&, Clipboard& clipboard) + void window_paste(Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) { - if (window.paste) - { - window_command_push(window, manager, settings, clipboard, window.paste); - return; - } - if (clipboard.is_empty()) return; + auto& storage = window.storage_get(document); + auto container = window_container_get(window, document); + auto maxIdBefore = container ? element_child_max_id_get(*container, window.elementType) : -1; + auto pasted = document.anm2; + std::string errorString{}; - auto paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) + if (!pasted.deserialize(window.elementType, clipboard.get(), true, &errorString, document.directory_get())) { - auto storage = &window.storage_get(document); - auto container = window_container_get(window, document.anm2); - auto maxIdBefore = container ? element_child_max_id_get(*container, window.elementType) : -1; - auto pasted = document.anm2; - std::string errorString{}; - - if (pasted.deserialize(window.elementType, clipboard.get(), true, &errorString, document.directory_get())) - { - document.snapshots.anm2_push(localize.get(window.pasteEdit)); - document.anm2 = std::move(pasted); - container = window_container_get(window, document.anm2); - auto maxIdAfter = container ? element_child_max_id_get(*container, window.elementType) : -1; - if (maxIdAfter > maxIdBefore) - { - window.newElementId = maxIdAfter; - storage->selection = {maxIdAfter}; - storage->reference = maxIdAfter; - } - document.change(window.changeType); - return; - } - - if (window.deserializeFailedToast) toast_log(Level::ERROR, window.deserializeFailedToast, errorString); - }; - - window_command_push(window, manager, settings, clipboard, paste); - } - - void window_remove_unused(Window& window, Manager& manager, Settings& settings, Document&, Clipboard& clipboard) - { - auto removeUnused = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto unused = document.anm2.element_unused(window.elementType); - if (unused.empty()) return; - - auto behavior = [&]() - { - auto container = window_container_get(window, document.anm2); - if (!container) return; - for (auto id : unused) - element_child_id_erase(*container, window.elementType, id); - }; - - window_edit(window, document, localize.get(window.removeUnusedEdit), behavior); - }; - - window_command_push(window, manager, settings, clipboard, removeUnused); - } - - void window_add(Window& window, Manager& manager, Settings& settings, Document&, Clipboard& clipboard) - { - if (window.add) - { - window_command_push(window, manager, settings, clipboard, window.add); + toast_log(Level::ERROR, window.deserializeFailedToast, errorString); return; } - if (window.properties_open) window.properties_open(manager, -1); + window_edit(document, window.changeType, localize.get(window.pasteEdit), + [&]() + { + document.anm2 = std::move(pasted); + container = window_container_get(window, document); + auto maxIdAfter = container ? element_child_max_id_get(*container, window.elementType) : -1; + if (maxIdAfter <= maxIdBefore) return; + window.newElementId = maxIdAfter; + storage.selection = {maxIdAfter}; + storage.reference = maxIdAfter; + if (window.row_select) window.row_select(window, document, maxIdAfter); + }); } - void window_command_run(Window& window, Manager& manager, Settings& settings, Document&, Clipboard& clipboard, - const Window::Command& command) + void window_remove_unused(Window& window, Manager&, Settings&, Document& document, Clipboard&) { - window_command_push(window, manager, settings, clipboard, command); + auto unused = document.anm2.element_unused(window.elementType); + auto container = window_container_get(window, document); + if (unused.empty() || !container) return; + window_edit(document, window.changeType, localize.get(window.removeUnusedEdit), + [&]() + { + for (auto id : unused) + element_child_id_erase(*container, window.elementType, id); + }); } - void window_properties(Window& window, Manager& manager, int id) + bool is_window_group_selected(const Window& window) { - if (window.properties_open) window.properties_open(manager, id); + return window.elementType == ElementType::ANIMATION && !window.selection.empty(); } - void window_scroll_to_item(float rowHeight, bool isTarget) + bool is_window_item_selected(Window& window, Document& document) { - if (!isTarget) return; - auto windowHeight = ImGui::GetWindowHeight(); - auto targetTop = ImGui::GetCursorPosY(); - auto targetBottom = targetTop + rowHeight; - auto visibleTop = ImGui::GetScrollY(); - auto visibleBottom = visibleTop + windowHeight; - if (targetTop < visibleTop) - ImGui::SetScrollY(targetTop); - else if (targetBottom > visibleBottom) - ImGui::SetScrollY(targetBottom - windowHeight); + return !window.storage_get(document).selection.empty() || is_window_group_selected(window); } - int window_arrow_selection_get(const std::vector& ids, int reference, const std::set& selection) + void window_properties(Window& window, Manager& manager, Settings& settings, Clipboard& clipboard, int id) { - if (ids.empty()) return -1; - auto current = reference; - if (current == -1 && !selection.empty()) current = *selection.begin(); - auto it = std::find(ids.begin(), ids.end(), current); + if (window.properties) + window_command_push(window, manager, settings, clipboard, window.properties); + else if (window.properties_open) + window.properties_open(manager, id); + } + + void window_activate(Window& window, Manager& manager, Settings& settings, Clipboard& clipboard, int id) + { + if (window_flag_has(window.flags, WINDOW_PROPERTIES)) window_properties(window, manager, settings, clipboard, id); + if (window_flag_has(window.flags, WINDOW_OPEN_DIRECTORY)) + window_command_push(window, manager, settings, clipboard, window.open); + } + + Action window_action_make(Window& window, Manager& manager, Settings& settings, Document& document, + Clipboard& clipboard, const WindowFlagInfo& info, bool isFooter) + { + auto selection = &window.storage_get(document).selection; + auto command = window.*(info.command); + auto window_push = [&window, &manager, &settings, &clipboard](Window::Command command) + { + return [&window, &manager, &settings, &clipboard, command]() + { window_command_push(window, manager, settings, clipboard, command); }; + }; + + std::function isEnabled = [selection]() { return selection->size() == 1; }; + std::function run = window_push(command); + auto isItemSelected = [&window, &document]() { return is_window_item_selected(window, document); }; + auto isAny = [selection]() { return !selection->empty(); }; + + switch (info.flag) + { + case WINDOW_RENAME: + isEnabled = [&window, selection]() + { + return selection->size() == 1 || + (window.elementType == ElementType::ANIMATION && selection->empty() && window.selection.size() == 1); + }; + run = [&window, selection]() + { + window.renameQueued = + selection->size() == 1 ? *selection->begin() : window_group_key_get(*window.selection.begin()); + }; + break; + case WINDOW_PROPERTIES: + run = [&window, &manager, &settings, &clipboard, selection]() + { window_properties(window, manager, settings, clipboard, *selection->begin()); }; + break; + case WINDOW_ADD: + isEnabled = []() { return true; }; + if (!command && window.properties_open) run = [&window, &manager]() { window.properties_open(manager, -1); }; + break; + case WINDOW_REMOVE_UNUSED: + isEnabled = []() { return true; }; + if (!command) run = window_push(window_remove_unused); + break; + case WINDOW_COPY: + isEnabled = isItemSelected; + if (!command) run = [&window, &document, &clipboard]() { window_copy(window, document, clipboard); }; + break; + case WINDOW_PASTE: + isEnabled = [&clipboard]() { return !clipboard.is_empty(); }; + if (!command) run = window_push(window_paste); + break; + case WINDOW_DUPLICATE: + case WINDOW_CUT: + case WINDOW_REMOVE: + isEnabled = isItemSelected; + break; + case WINDOW_RELOAD: + case WINDOW_TRIM: + case WINDOW_SAVE: + case WINDOW_GROUP: + isEnabled = isAny; + break; + case WINDOW_MERGE: + isEnabled = [selection]() { return selection->size() > 1; }; + if (window.merge_open && (isFooter || window.elementType != ElementType::ANIMATION) && + !is_window_group_selected(window)) + run = window_push(window.merge_open); + break; + default: + break; + } + + if (auto enabled = window.enabled.find(info.flag); enabled != window.enabled.end()) + isEnabled = [&window, &document, is_enabled = enabled->second]() { return is_enabled(window, document); }; + + auto tooltip = window.tooltips.find(info.flag); + return action_make(info.action, std::move(isEnabled), std::move(run), + tooltip == window.tooltips.end() ? STRING_UNDEFINED : tooltip->second, + info.flag == WINDOW_PLAY ? -1 : ACTION_COUNT); + } + + Actions window_context_actions_get(Window& window, Manager& manager, Settings& settings, Document& document, + Clipboard& clipboard, bool isUndoRedoIncluded) + { + Actions actions{}; + if (isUndoRedoIncluded) + { + actions_undo_redo_add(actions, manager, document); + actions.separator(); + } + + for (const auto& info : WINDOW_FLAG_INFOS) + { + if (info.flag == WINDOW_CUT) actions.separator(); + if (window_flag_has(window.flags, info.flag)) + actions.add(window_action_make(window, manager, settings, document, clipboard, info, false)); + } + return actions; + } + + void window_footer_draw(Window& window, Manager& manager, Settings& settings, Document& document, + Clipboard& clipboard) + { + for (const auto& row : window.footer) + { + auto widgetSize = widget_size_with_row_get((int)row.size()); + bool isSameLine{}; + for (auto flag : row) + { + auto info = std::ranges::find(WINDOW_FLAG_INFOS, flag, &WindowFlagInfo::flag); + auto action = window_action_make(window, manager, settings, document, clipboard, *info, true); + action_button_draw(action, manager, settings, widgetSize, isSameLine); + } + } + } + + int window_arrow_selection_get(const std::vector& ids, const Storage& storage) + { + if (ids.empty() || !ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) || + !(ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) + return -1; + auto current = + storage.reference == -1 && !storage.selection.empty() ? *storage.selection.begin() : storage.reference; + auto it = std::ranges::find(ids, current); auto index = it == ids.end() ? 0 : (int)std::distance(ids.begin(), it); auto delta = ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) ? -1 : 1; - index = std::clamp(index + delta, 0, (int)ids.size() - 1); - return ids[index]; + return ids[std::clamp(index + delta, 0, (int)ids.size() - 1)]; + } + + int window_selection_start(Window& window, Document& document, const std::vector& arrowIds) + { + auto& storage = window.storage_get(document); + storage.selection.set_index_map(&window.order); + storage.selection.start(window.order.size()); + if (ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) + { + storage.selection.clear(); + storage.reference = -1; + if (window.row_select) window.row_select(window, document, -1); + } + return window_arrow_selection_get(arrowIds, storage); + } + + void window_selection_finish(Window& window, Manager& manager, Settings& settings, Clipboard& clipboard, + Document& document, int arrowSelectionId) + { + auto& storage = window.storage_get(document); + storage.selection.finish(); + storage.selection.set_index_map(nullptr); + if (arrowSelectionId != -1) + { + storage.selection = {arrowSelectionId}; + storage.reference = arrowSelectionId; + if (window.row_select) window.row_select(window, document, arrowSelectionId); + } + if (shortcut(manager.chords[SHORTCUT_CONFIRM], shortcut::FOCUSED) && storage.selection.size() == 1) + window_activate(window, manager, settings, clipboard, *storage.selection.begin()); + } + + void window_row_select(Window& window, Document& document, int key) + { + window.storage_get(document).reference = key; + if (window.row_select) window.row_select(window, document, key); + } + + void window_scroll_update(Window& window, int key, int scrollTargetId) + { + if ((window.newElementId != key && window.scrollQueued != key && scrollTargetId != key) || is_drag_drop_active()) + return; + ImGui::SetScrollHereY(SCROLL_CENTER); + if (window.newElementId == key) window.newElementId = -1; + if (window.scrollQueued == key) window.scrollQueued = -1; + } + + void window_tooltip_update(Window& window, Resources& resources, Document& document, const Element& element) + { + if (!window.tooltip_draw) return; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); + if (ImGui::BeginItemTooltip()) + { + window.tooltip_draw(document, resources, element); + ImGui::EndTooltip(); + } + ImGui::PopStyleVar(2); + } + + bool window_row_draw(Window& window, Manager& manager, Resources& resources, Document& document, Element& element, + int key, int index, int arrowSelectionId) + { + auto& storage = window.storage_get(document); + auto isSelected = storage.selection.contains(key) || arrowSelectionId == key; + auto isReferenced = + window_flag_has(window.flags, WINDOW_REFERENCE_ITALIC) && (storage.reference == key || arrowSelectionId == key); + auto font = window.row_font_get ? window.row_font_get(document, element, key) + : isReferenced ? resource::font::ITALICS + : resource::font::REGULAR; + auto isFontPushed = font != resource::font::REGULAR; + auto label = window.row_label_get ? window.row_label_get(document, element) : element.name; + + ImGui::PushID(key); + ImGui::SetNextItemSelectionUserData(index); + if (isFontPushed) ImGui::PushFont(resources.fonts[font].get(), resource::font::SIZE); + if (arrowSelectionId == key) ImGui::SetKeyboardFocusHere(); + + bool isActivated{}; + if (window_flag_has(window.flags, WINDOW_RENAME)) + { + if (window.newElementId == key || window.renameQueued == key) + { + window.renameState = RENAME_FORCE_EDIT; + window.renameQueued = -1; + } + + auto isRenaming = window.renameId == key; + auto renameLabel = + std::format("###Document #{} Window #{} Element #{}", manager.selected, (int)window.elementType, key); + isActivated = selectable_input_text(label, renameLabel, isRenaming ? window.renameText : element.name, isSelected, + ImGuiSelectableFlags_None, window.renameState); + if (isActivated && window.renameState == RENAME_BEGIN) + { + window.renameId = key; + window.renameText = element.name; + } + else if (isActivated && window.renameState == RENAME_FINISHED) + { + if (isRenaming) window_rename_finish(window, manager, key, (int)window.order.size(), window.renameText); + window.renameId = -1; + window.renameText.clear(); + } + } + else + isActivated = ImGui::Selectable(label.c_str(), isSelected); + + if (isActivated || ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right)) + window_row_select(window, document, key); + if (isFontPushed) ImGui::PopFont(); + window_scroll_update(window, key, arrowSelectionId); + + if (window_flag_has(window.flags, WINDOW_PROPERTIES) && ImGui::IsItemHovered() && + ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && window.properties_open) + window.properties_open(manager, key); + + auto isBreak = window.row_drag_drop_update && window.row_drag_drop_update(window, manager, document, element, key); + window_tooltip_update(window, resources, document, element); + ImGui::PopID(); + return isBreak; + } + + void window_tooltip_name_draw(Resources& resources, const std::string& name) + { + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(name.c_str()); + ImGui::PopFont(); + } + + void window_tooltip_image_draw(const WindowCardImage& image, const std::function& info_draw) + { + auto maxPreviewSize = to_vec2(ImGui::GetMainViewport()->Size) * PREVIEW_VIEWPORT_FRACTION; + auto previewSize = glm::max(image.size, vec2(1.0f)); + previewSize *= glm::min(1.0f, glm::min(maxPreviewSize.x / previewSize.x, maxPreviewSize.y / previewSize.y)); + + auto childFlags = ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY; + auto noScrollFlags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + if (ImGui::BeginChild("##Tooltip Image Child", to_imvec2(previewSize), childFlags, noScrollFlags)) + ImGui::ImageWithBg(image.texture->id, to_imvec2(previewSize), to_imvec2(image.uvMin), to_imvec2(image.uvMax), + ImVec4(), image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID); + ImGui::EndChild(); + ImGui::PopStyleVar(); + + ImGui::SameLine(); + if (ImGui::BeginChild("##Tooltip Info Child", ImVec2(), ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY, + noScrollFlags)) + info_draw(); + ImGui::EndChild(); + } + + void window_cards_draw(Window& window, Manager& manager, Settings& settings, Resources& resources, + Clipboard& clipboard, Document& document, Element* container) + { + auto& storage = window.storage_get(document); + auto cardSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * window.cardLines); + auto style = ImGui::GetStyle(); + + window.order.clear(); + if (container) + for (auto& element : container->children) + if (element.type == window.elementType) window.order.push_back(element.id); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + auto arrowSelectionId = window_selection_start(window, document, window.order); + + for (int i = 0; i < (int)window.order.size(); i++) + { + auto id = window.order[i]; + auto element = child_id_get(*container, window.elementType, id); + if (!element) continue; + + ImGui::PushID(id); + if (arrowSelectionId == id) + { + auto targetTop = ImGui::GetCursorPosY(); + if (targetTop < ImGui::GetScrollY()) + ImGui::SetScrollY(targetTop); + else if (targetTop + cardSize.y > ImGui::GetScrollY() + ImGui::GetWindowHeight()) + ImGui::SetScrollY(targetTop + cardSize.y - ImGui::GetWindowHeight()); + ImGui::SetNextWindowFocus(); + } + + auto isBreak = false; + if (ImGui::BeginChild("##Card Child", cardSize, ImGuiChildFlags_Borders)) + { + auto cursorPos = ImGui::GetCursorPos(); + auto isSelected = storage.selection.contains(id) || arrowSelectionId == id; + auto isReferenced = id == storage.reference || arrowSelectionId == id; + auto image = window.card_image_get(document, resources, *element); + auto tint = image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID; + auto label = window.row_label_get ? window.row_label_get(document, *element) : element->name; + + ImGui::SetNextItemSelectionUserData(i); + ImGui::SetNextItemStorageID(id); + if (arrowSelectionId == id) ImGui::SetKeyboardFocusHere(); + if (ImGui::Selectable("##Card Selectable", isSelected, 0, cardSize) || + ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right)) + window_row_select(window, document, id); + if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + window_activate(window, manager, settings, clipboard, id); + + if (window.tooltip_draw && ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip) && + !ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + auto textWidth = ImGui::CalcTextSize(label.c_str()).x; + ImGui::SetNextWindowSize(ImVec2(textWidth + window.tooltipItemSpacing.x + + window.tooltipWindowPadding.x * TOOLTIP_PADDING_MULTIPLIER, + 0), + ImGuiCond_Appearing); + window_tooltip_update(window, resources, document, *element); + } + + isBreak = window.row_drag_drop_update && window.row_drag_drop_update(window, manager, document, *element, i); + + auto aspectRatio = image.size.y != 0.0f ? image.size.x / image.size.y : 1.0f; + auto imageSize = ImVec2(cardSize.y, cardSize.y); + if (imageSize.x / imageSize.y > aspectRatio) + imageSize.x = imageSize.y * aspectRatio; + else + imageSize.y = imageSize.x / aspectRatio; + ImGui::SetCursorPos(cursorPos); + ImGui::ImageWithBg(image.texture->id, imageSize, to_imvec2(image.uvMin), to_imvec2(image.uvMax), ImVec4(), + tint); + + ImGui::SetCursorPos( + ImVec2(cardSize.y + style.ItemSpacing.x, cardSize.y - cardSize.y / 2 - ImGui::GetTextLineHeight() / 2)); + if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); + ImGui::TextUnformatted(label.c_str()); + if (isReferenced) ImGui::PopFont(); + } + ImGui::EndChild(); + + window_scroll_update(window, id, -1); + ImGui::PopID(); + if (isBreak) break; + } + + ImGui::PopStyleVar(); + window_selection_finish(window, manager, settings, clipboard, document, arrowSelectionId); + } + + void window_list_draw(Window& window, Manager& manager, Settings& settings, Resources& resources, + Clipboard& clipboard, Document& document) + { + std::vector elements{}; + window.order.clear(); + if (auto container = window_container_get(window, document)) + for (auto& element : container->children) + if (element.type == window.elementType) + { + window.order.push_back(window.element_key_get ? window.element_key_get(element, (int)elements.size()) + : element.id); + elements.push_back(&element); + } + + auto arrowSelectionId = window_selection_start(window, document, window.order); + for (int i = 0; i < (int)elements.size(); ++i) + if (window_row_draw(window, manager, resources, document, *elements[i], window.order[i], i, arrowSelectionId)) + break; + window_selection_finish(window, manager, settings, clipboard, document, arrowSelectionId); } std::filesystem::path window_asset_path_get(Document& document, const std::filesystem::path& path) { - auto loadPath = path::backslash_handle(path); - return path::backslash_replace(path::make_relative(loadPath, document.directory_get())); + return path::backslash_replace(path::make_relative(path::backslash_handle(path), document.directory_get())); } void window_directory_open(Dialog& dialog, Document& document, const std::filesystem::path& path) @@ -371,1010 +598,23 @@ namespace anm2ed::imgui dialog.file_explorer_open(target); } - int window_animation_count_get(Anm2& anm2) + PopupButton window_popup_buttons_draw(Manager& manager, const char* confirmLabel, bool isConfirmEnabled, + StringType cancelLabel) { - int count{}; - auto animations = anm2.element_get(ElementType::ANIMATIONS); - if (!animations) return count; - for (auto& animation : animations->children) - if (animation.type == ElementType::ANIMATION) ++count; - return count; - } + auto widgetSize = widget_size_with_row_get(2); + auto result = PopupButton::NONE; - int window_animation_child_index_get(const Element& animations, int animationIndex) - { - int current{}; - for (int i = 0; i < (int)animations.children.size(); ++i) - { - if (animations.children[i].type != ElementType::ANIMATION) continue; - if (current == animationIndex) return i; - ++current; - } - return -1; - } + ImGui::BeginDisabled(!isConfirmEnabled); + shortcut(manager.chords[SHORTCUT_CONFIRM]); + if (ImGui::Button(confirmLabel, widgetSize)) result = PopupButton::CONFIRM; + ImGui::EndDisabled(); - int window_animation_child_insert_index_get(const Element& animations, int animationIndex) - { - if (animationIndex <= 0) - { - for (int i = 0; i < (int)animations.children.size(); ++i) - if (animations.children[i].type == ElementType::ANIMATION) return i; - return (int)animations.children.size(); - } - int current{}; - for (int i = 0; i < (int)animations.children.size(); ++i) - { - if (animations.children[i].type != ElementType::ANIMATION) continue; - if (current == animationIndex) return i; - ++current; - } - 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{}; - for (int i = 0; i < (int)animations.children.size(); ++i) - { - if (animations.children[i].type != ElementType::ANIMATION) continue; - if (i == childIndex) return current; - ++current; - } - 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{}; - for (const auto& item : animations.children) - if (item.type == ElementType::GROUP) result.insert(item.id); + ImGui::SameLine(); + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(cancelLabel), widgetSize)) result = PopupButton::CANCEL; 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); - } - - std::vector window_animation_groupable_indices_get(Document& document) - { - std::vector result{}; - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - if (!animations || document.animation.selection.empty()) return result; - - auto groupIds = window_animation_group_ids_get(*animations); - int index{}; - for (const auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - if (document.animation.selection.contains(index)) - { - if (is_window_animation_grouped(groupIds, animation)) return {}; - result.push_back(index); - } - ++index; - } - if (result.size() != document.animation.selection.size()) return {}; - return result; - } - - int window_animation_group_key_get(int groupId) { return -groupId - 2; } - - bool is_window_animation_group_key(int key) { return key <= -2; } - - int window_animation_group_id_from_key_get(int key) { return -key - 2; } - - bool is_window_animation_group_selected(const Window& window) - { - return window.elementType == ElementType::ANIMATION && !window.selection.empty(); - } - - std::set window_animation_group_indices_get(const Element& animations, int groupId) - { - std::set result{}; - int animationIndex{}; - for (const auto& animation : animations.children) - { - if (animation.type != ElementType::ANIMATION) continue; - if (animation.groupId == groupId) result.insert(animationIndex); - ++animationIndex; - } - return result; - } - - std::set window_animation_selected_indices_get(Document& document, const Window& window) - { - std::set result(document.animation.selection.begin(), document.animation.selection.end()); - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - if (!animations || window.elementType != ElementType::ANIMATION) return result; - - for (auto groupId : window.selection) - { - auto indices = window_animation_group_indices_get(*animations, groupId); - result.insert(indices.begin(), indices.end()); - } - return result; - } - - std::set window_animation_merge_indices_get(Document& document, const std::set& keys, int reference) - { - std::set result{}; - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - - for (auto key : keys) - { - if (is_window_animation_group_key(key)) - { - if (!animations) continue; - auto indices = window_animation_group_indices_get(*animations, window_animation_group_id_from_key_get(key)); - result.insert(indices.begin(), indices.end()); - } - else - result.insert(key); - } - - result.erase(reference); - return result; - } - - void window_animation_groups_remove(Document& document, const std::set& groupIds) - { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - if (!animations || groupIds.empty()) return; - - for (auto& item : animations->children) - if (item.type == ElementType::ANIMATION && groupIds.contains(item.groupId)) item.groupId = -1; - std::erase_if(animations->children, - [&](const Element& item) { return item.type == ElementType::GROUP && groupIds.contains(item.id); }); - } - - std::string window_animation_clipboard_text_get(Document& document, const Window& window) - { - std::string clipboardText{}; - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - if (!animations) return clipboardText; - - int animationIndex{}; - for (const auto& item : animations->children) - { - if (item.type == ElementType::GROUP) - { - if (window.selection.contains(item.id)) clipboardText += element_to_string(item); - } - else if (item.type == ElementType::ANIMATION) - { - if (document.animation.selection.contains(animationIndex) || window.selection.contains(item.groupId)) - clipboardText += element_to_string(item); - ++animationIndex; - } - } - - return clipboardText; - } - - bool is_window_item_selected(Window& window, Document& document) - { - return !window.storage_get(document).selection.empty() || is_window_animation_group_selected(window); - } - - bool is_window_item_renameable(Window& window, Document& document) - { - auto& selection = window.storage_get(document).selection; - return selection.size() == 1 || - (window.elementType == ElementType::ANIMATION && selection.empty() && window.selection.size() == 1); - } - - bool is_window_merge_available(Window& window, Document& document) - { - auto& selection = window.storage_get(document).selection; - if (window.elementType != ElementType::ANIMATION) return !selection.empty(); - return !window_animation_selected_indices_get(document, window).empty(); - } - - int window_animations_merge(Document& document, const AnimationMergeOptions& options, - const std::set* quickSelection = nullptr, - const std::set* quickGroupSelection = nullptr) - { - auto& anm2 = document.anm2; - auto& selection = document.animation.selection; - auto& reference = document.reference; - auto& overlayIndex = document.overlayIndex; - auto& overlayDocumentId = document.overlayDocumentId; - int merged{-1}; - - document.snapshots.anm2_push(localize.get(EDIT_MERGE_ANIMATIONS)); - if (options.selection.empty()) - { - auto selected = quickSelection ? *quickSelection : std::set(selection.begin(), selection.end()); - auto isQuickGroupMerge = quickGroupSelection && !quickGroupSelection->empty(); - if ((overlayDocumentId == 0 || overlayDocumentId == document.tabId) && selected.contains(overlayIndex)) - { - overlayIndex = -1; - overlayDocumentId = 0; - } - - if (selected.size() > 1) - merged = anm2.animations_merge(*selected.begin(), selected); - else if (selected.size() == 1 && isQuickGroupMerge) - merged = *selected.begin(); - else if (selected.size() == 1 && *selected.begin() != window_animation_count_get(anm2) - 1) - { - auto start = *selected.begin(); - auto next = *selected.begin() + 1; - std::set animationSet{}; - animationSet.insert(start); - animationSet.insert(next); - merged = anm2.animations_merge(start, animationSet); - } - else - return -1; - - if (isQuickGroupMerge) window_animation_groups_remove(document, *quickGroupSelection); - } - else - { - auto mergeSelection = window_animation_merge_indices_get(document, options.selection, options.reference); - if (mergeSelection.empty()) return -1; - if ((overlayDocumentId == 0 || overlayDocumentId == document.tabId) && mergeSelection.contains(overlayIndex)) - { - overlayIndex = -1; - overlayDocumentId = 0; - } - merged = anm2.animations_merge(options.reference, mergeSelection, options.type, options.isDeleteAnimationsAfter); - } - - if (merged == -1) return -1; - selection = {merged}; - reference = {merged}; - document.change(Document::ANIMATIONS); - return merged; - } - - void window_spritesheets_merge(Document& document, const std::set& ids, const SpritesheetMergeOptions& options) - { - if (ids.size() <= 1) return; - - auto behavior = [&]() - { - auto baseID = *ids.begin(); - if (document.spritesheets_merge(ids, options.isAppendRight, options.isMakeRegions, options.isMakePrimaryRegion, - options.regionOrigin)) - { - document.spritesheet.selection = {baseID}; - document.spritesheet.reference = baseID; - document.region.reference = -1; - document.region.selection.clear(); - toast_log(Level::INFO, TOAST_MERGE_SPRITESHEETS); - } - else - { - toast_log(Level::ERROR, TOAST_MERGE_SPRITESHEETS_FAILED); - } - }; - - document.snapshots.anm2_textures_push(localize.get(EDIT_MERGE_SPRITESHEETS)); - behavior(); - document.change(Document::ALL); - } - - void window_spritesheet_pack(Document& document, int id, int padding) - { - if (id == -1) return; - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); - if (!spritesheet) return; - bool isRegionsEmpty = true; - for (auto& child : spritesheet->children) - if (child.type == ElementType::REGION) isRegionsEmpty = false; - if (isRegionsEmpty) return; - - auto behavior = [&]() - { - if (document.spritesheet_pack(id, std::max(0, padding))) - { - toast_log(Level::INFO, TOAST_PACK_SPRITESHEET); - } - else - { - toast_log(Level::ERROR, TOAST_PACK_SPRITESHEET_FAILED); - } - }; - - document.snapshots.anm2_textures_push(localize.get(EDIT_PACK_SPRITESHEET)); - behavior(); - document.change(Document::SPRITESHEETS); - } - - void window_spritesheets_save(Document& document, const std::set& ids) - { - if (ids.empty()) return; - - for (auto& id : ids) - { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); - auto texture = document.texture_get(id); - if (!spritesheet || !texture) continue; - auto pathString = path::to_utf8(spritesheet->path); - WorkingDirectory workingDirectory(document.directory_get()); - path::ensure_directory(spritesheet->path.parent_path()); - if (texture->write_png(spritesheet->path)) - { - document.spritesheet_hash_set_saved(id); - toast_log(Level::INFO, TOAST_SAVE_SPRITESHEET, id, pathString); - } - else - { - toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); - } - } - } - - 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) - { - toast_log(Level::ERROR, TOAST_EXPORT_REGION_PATH_EMPTY); - return false; - } - - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, options.spritesheetId); - auto region = spritesheet ? child_id_get(*spritesheet, ElementType::REGION, options.regionId) : nullptr; - auto texture = document.texture_get(options.spritesheetId); - if (!spritesheet || !region || !texture || !texture->is_valid()) - { - toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, "", pathString); - return false; - } - - auto sourceRegion = *region; - auto regionName = sourceRegion.name; - std::vector pixels{}; - ivec2 exportSize{}; - if (!window_region_pixels_get(sourceRegion, *texture, pixels, exportSize)) - { - toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, 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())) - { - toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, regionName, pathString); - return false; - } - } - - exportedSpritesheetId = -1; - if (options.isMakeSpritesheet || options.isRemoveCurrent) - { - document.snapshots.anm2_textures_push(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); - } - - toast_log(Level::INFO, TOAST_EXPORT_REGION, regionName, pathString); - return true; - } - - int window_footer_button_count_get(const Window& window) - { - int count{}; - if (window_flag_has(window.flags, WINDOW_ADD)) ++count; - if (window_flag_has(window.flags, WINDOW_DUPLICATE)) ++count; - if (window_flag_has(window.flags, WINDOW_MERGE)) ++count; - if (window_flag_has(window.flags, WINDOW_REMOVE)) ++count; - if (window_flag_has(window.flags, WINDOW_REMOVE_UNUSED)) ++count; - if (window_flag_has(window.flags, WINDOW_DEFAULT)) ++count; - return count; - } - - Actions window_footer_actions_get(Window& window, Manager& manager, Settings& settings, Document& document, - Clipboard& clipboard) - { - Actions actions{}; - auto& selection = window.storage_get(document).selection; - - if (window_flag_has(window.flags, WINDOW_ADD)) - actions.add( - ACTION_ADD, []() { return true; }, [&]() { window_add(window, manager, settings, document, clipboard); }, - window.addTooltip); - - if (window_flag_has(window.flags, WINDOW_DUPLICATE)) - actions.add( - ACTION_DUPLICATE, [&]() { return is_window_item_selected(window, document); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.duplicate); }, - window.duplicateTooltip); - - if (window_flag_has(window.flags, WINDOW_MERGE)) - actions.add( - ACTION_MERGE, - [&]() - { - if (window.elementType == ElementType::ANIMATION) - { - if (is_window_animation_group_selected(window)) return is_window_merge_available(window, document); - return selection.size() == 1; - } - return selection.size() == 1; - }, - [&]() - { - auto command = - window.merge_open && !is_window_animation_group_selected(window) ? window.merge_open : window.merge; - window_command_run(window, manager, settings, document, clipboard, command); - }, - window.mergeTooltip); - - if (window_flag_has(window.flags, WINDOW_REMOVE)) - actions.add( - ACTION_REMOVE, [&]() { return !selection.empty() || is_window_animation_group_selected(window); }, [&]() - { window_command_run(window, manager, settings, document, clipboard, window.remove); }, window.removeTooltip); - - if (window_flag_has(window.flags, WINDOW_REMOVE_UNUSED)) - actions.add( - ACTION_REMOVE_UNUSED, []() { return true; }, - [&]() { window_remove_unused(window, manager, settings, document, clipboard); }, window.removeUnusedTooltip); - - if (window_flag_has(window.flags, WINDOW_DEFAULT)) - actions.add( - ACTION_DEFAULT, [&]() { return selection.size() == 1; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.default_set); }, - window.defaultTooltip); - - return actions; - } - - Actions window_context_actions_get(Window& window, Manager& manager, Settings& settings, Document& document, - Clipboard& clipboard, bool isUndoRedoIncluded = true) - { - Actions actions{}; - auto& selection = window.storage_get(document).selection; - - if (isUndoRedoIncluded) - { - actions_undo_redo_add(actions, manager, document); - actions.separator(); - } - - if (window_flag_has(window.flags, WINDOW_RENAME)) - actions.add( - ACTION_RENAME, [&]() { return is_window_item_renameable(window, document); }, - [&]() - { - if (selection.size() == 1) - window.renameQueued = *selection.begin(); - else if (window.elementType == ElementType::ANIMATION && window.selection.size() == 1) - window.renameQueued = window_animation_group_key_get(*window.selection.begin()); - }); - if (window_flag_has(window.flags, WINDOW_PROPERTIES)) - actions.add( - ACTION_PROPERTIES, [&]() { return selection.size() == 1; }, - [&]() { window_properties(window, manager, *selection.begin()); }); - if (window_flag_has(window.flags, WINDOW_ADD)) - actions.add( - ACTION_ADD, []() { return true; }, [&]() { window_add(window, manager, settings, document, clipboard); }); - if (window_flag_has(window.flags, WINDOW_DUPLICATE)) - actions.add( - ACTION_DUPLICATE, [&]() { return is_window_item_selected(window, document); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.duplicate); }); - if (window_flag_has(window.flags, WINDOW_MERGE)) - actions.add( - ACTION_MERGE, [&]() { return is_window_merge_available(window, document); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.merge); }); - if (window_flag_has(window.flags, WINDOW_GROUP)) - actions.add( - ACTION_GROUP, - [&]() - { - if (window.elementType == ElementType::ANIMATION) - return !window_animation_groupable_indices_get(document).empty(); - return !selection.empty(); - }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.group); }); - if (window_flag_has(window.flags, WINDOW_REMOVE)) - actions.add( - ACTION_REMOVE, [&]() { return !selection.empty() || is_window_animation_group_selected(window); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); - if (window_flag_has(window.flags, WINDOW_REMOVE_UNUSED)) - actions.add( - ACTION_REMOVE_UNUSED, []() { return true; }, - [&]() { window_remove_unused(window, manager, settings, document, clipboard); }); - if (window_flag_has(window.flags, WINDOW_DEFAULT)) - actions.add( - ACTION_DEFAULT, [&]() { return selection.size() == 1; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.default_set); }); - - actions.separator(); - - if (window_flag_has(window.flags, WINDOW_CUT)) - actions.add( - ACTION_CUT, [&]() { return is_window_item_selected(window, document); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.cut); }); - if (window_flag_has(window.flags, WINDOW_COPY)) - actions.add( - ACTION_COPY, [&]() { return is_window_item_selected(window, document); }, - [&]() { window_copy(window, manager, settings, document, clipboard); }); - if (window_flag_has(window.flags, WINDOW_PASTE)) - actions.add( - ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, - [&]() { window_paste(window, manager, settings, document, clipboard); }); - - return actions; - } - - void window_footer_draw(Window& window, Manager& manager, Settings& settings, Document& document, - Clipboard& clipboard) - { - auto actions = window_footer_actions_get(window, manager, settings, document, clipboard); - auto buttonCount = (int)actions.items.size(); - if (buttonCount == 0) return; - - auto widgetSize = widget_size_with_row_get(buttonCount); - bool isSameLine{}; - for (auto& action : actions.items) - action_button_draw(action, manager, settings, widgetSize, isSameLine); - } - - void window_context_menu_draw(Window& window, Manager& manager, Settings& settings, Document& document, - Clipboard& clipboard) - { - auto actions = window_context_actions_get(window, manager, settings, document, clipboard); - actions_context_window_draw("##Context Menu", actions, settings); - } - - std::string window_rename_format_get(Window& window, Manager& manager, int id) - { - return std::format("###Document #{} Window #{} Element #{}", manager.selected, (int)window.elementType, id); - } - - void window_rows_draw(Window& window, Manager& manager, Resources& resources, Document& document) - { - auto container = window_container_get(window, document.anm2); - auto& storage = window.storage_get(document); - auto& selection = storage.selection; - std::vector ids{}; - if (container) - for (auto& element : container->children) - if (element.type == window.elementType) - { - auto key = window.element_key_get ? window.element_key_get(element, (int)ids.size()) : element.id; - ids.push_back(key); - } - auto count = (int)ids.size(); - int index{}; - int scrollTargetId = -1; - int arrowSelectionId = -1; - - selection.start(count); - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && - (ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) - { - auto nextId = window_arrow_selection_get(ids, storage.reference, selection); - if (nextId != -1) - { - arrowSelectionId = nextId; - scrollTargetId = nextId; - } - } - - if (container) - { - for (auto& element : container->children) - { - if (element.type != window.elementType) continue; - auto key = window.element_key_get ? window.element_key_get(element, index) : element.id; - auto isSelected = selection.contains(key) || arrowSelectionId == key; - auto isReferenced = window_flag_has(window.flags, WINDOW_REFERENCE_ITALIC) && - (storage.reference == key || arrowSelectionId == key); - auto font = window.row_font_get ? window.row_font_get(document, element, key) - : isReferenced ? resource::font::ITALICS - : resource::font::REGULAR; - auto isFontPushed = font != resource::font::REGULAR; - - ImGui::PushID(key); - ImGui::SetNextItemSelectionUserData(key); - auto label = window.row_label_get ? window.row_label_get(document, element) : element.name; - if (isFontPushed) ImGui::PushFont(resources.fonts[font].get(), resource::font::SIZE); - if (scrollTargetId == key) ImGui::SetKeyboardFocusHere(); - - if (window_flag_has(window.flags, WINDOW_RENAME)) - { - if (window.newElementId == key || window.renameQueued == key) - { - window.renameState = RENAME_FORCE_EDIT; - window.renameQueued = -1; - } - - auto isRenaming = window.renameId == key; - auto& name = isRenaming ? window.renameText : element.name; - bool isActivated{}; - if (selectable_input_text(label, window_rename_format_get(window, manager, key), name, isSelected, - ImGuiSelectableFlags_None, window.renameState)) - { - isActivated = true; - if (window.renameState == RENAME_BEGIN) - { - window.renameId = key; - window.renameText = element.name; - } - else if (window.renameState == RENAME_FINISHED) - { - if (isRenaming) window_rename_finish(window, manager, key, count, window.renameText); - window.renameId = -1; - window.renameText.clear(); - } - } - auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); - if (isActivated || isClicked) - { - storage.reference = key; - if (window.row_select) window.row_select(window, document, key); - } - } - else - { - auto isActivated = ImGui::Selectable(label.c_str(), isSelected); - auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); - if (isActivated || isClicked) - { - storage.reference = key; - if (window.row_select) window.row_select(window, document, key); - } - } - - if (isFontPushed) ImGui::PopFont(); - - if ((window.newElementId == key || window.scrollQueued == key || scrollTargetId == key) && - !is_drag_drop_active()) - { - ImGui::SetScrollHereY(0.5f); - if (window.newElementId == key) window.newElementId = -1; - if (window.scrollQueued == key) window.scrollQueued = -1; - } - - if (window_flag_has(window.flags, WINDOW_PROPERTIES) && ImGui::IsItemHovered() && - ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) - window_properties(window, manager, key); - - if (window.row_drag_drop_update && window.row_drag_drop_update(window, manager, document, element, key)) - { - ImGui::PopID(); - break; - } - - if (window.tooltip_draw) - { - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); - if (ImGui::BeginItemTooltip()) - { - window.tooltip_draw(document, resources, element); - ImGui::EndTooltip(); - } - ImGui::PopStyleVar(2); - } - - ImGui::PopID(); - ++index; - } - } - - selection.finish(); - if (arrowSelectionId != -1) - { - selection = {arrowSelectionId}; - storage.reference = arrowSelectionId; - if (window.row_select) window.row_select(window, document, arrowSelectionId); - } - if (shortcut(manager.chords[SHORTCUT_CONFIRM], shortcut::FOCUSED) && - window_flag_has(window.flags, WINDOW_PROPERTIES) && selection.size() == 1) - window_properties(window, manager, *selection.begin()); - } - void window_update(Window& window, Manager& manager, Settings& settings, Resources& resources, Dialog& dialog, Clipboard& clipboard) { @@ -1384,46 +624,42 @@ namespace anm2ed::imgui if (ImGui::Begin(localize.get(window.title), &(settings.*window.isOpen))) { - if (window.begin_update) window.begin_update(window, manager, settings, resources, clipboard, *document); - - auto isAvailable = !window.is_available || window.is_available(*document); - if (!isAvailable) + if (window.is_available && !window.is_available(window, *document)) { if (window.unavailableText != STRING_UNDEFINED) ImGui::TextUnformatted(localize.get(window.unavailableText)); } else { - auto footerRows = window.footerRows != -1 ? window.footerRows - : window_footer_button_count_get(window) > 0 ? 1 - : 0; - auto childSize = size_without_footer_get(footerRows); + auto childSize = size_without_footer_get((int)window.footer.size()); auto style = ImGui::GetStyle(); window.tooltipWindowPadding = style.WindowPadding; window.tooltipItemSpacing = style.ItemSpacing; - if (window.isChildPaddingZero) ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - auto isChildOpen = ImGui::BeginChild(window.childLabel, childSize, true); - if (isChildOpen) + auto isCards = window.cardLines > 0; + if (isCards) ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + if (ImGui::BeginChild(window.childLabel, childSize, true)) { if (window.rows_update) - window.rows_update(window, manager, settings, resources, clipboard, *document, childSize); + window.rows_update(window, manager, settings, resources, clipboard, *document); + else if (isCards) + window_cards_draw(window, manager, settings, resources, clipboard, *document, + window_container_get(window, *document)); else - window_rows_draw(window, manager, resources, *document); + window_list_draw(window, manager, settings, resources, clipboard, *document); auto actions = window_context_actions_get(window, manager, settings, *document, clipboard, false); actions_shortcuts_update(actions, manager); - - if (!window.context_update) window_context_menu_draw(window, manager, settings, *document, clipboard); } ImGui::EndChild(); - if (window.isChildPaddingZero) ImGui::PopStyleVar(); + if (isCards) ImGui::PopStyleVar(); - if (window.context_update) window.context_update(window, manager, settings, resources, clipboard, *document); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && + ImGui::IsMouseReleased(ImGuiMouseButton_Right)) + ImGui::OpenPopup(CONTEXT_MENU_LABEL); + auto actions = window_context_actions_get(window, manager, settings, *document, clipboard, true); + actions_popup_draw(CONTEXT_MENU_LABEL, actions, settings); - if (window.footer_update) - window.footer_update(window, manager, settings, resources, clipboard, *document); - else - window_footer_draw(window, manager, settings, *document, clipboard); + window_footer_draw(window, manager, settings, *document, clipboard); if (window.body_update) window.body_update(window, manager, settings, resources, clipboard, *document); } } @@ -1432,3041 +668,4 @@ namespace anm2ed::imgui if (window.popup_update) window.popup_update(window, manager, settings, resources, clipboard, *document); if (window.post_update) window.post_update(window, manager, settings, resources, clipboard, *document); } - - Window animations_window_register() - { - Window window{}; - window.title = LABEL_ANIMATIONS_WINDOW; - window.isOpen = &Settings::windowIsAnimations; - window.changeType = Document::ANIMATIONS; - window.containerType = ElementType::ANIMATIONS; - window.elementType = ElementType::ANIMATION; - window.childLabel = "##Animations Child"; - window.addTooltip = TOOLTIP_ADD_ANIMATION; - window.duplicateTooltip = TOOLTIP_DUPLICATE_ANIMATION; - window.mergeTooltip = TOOLTIP_OPEN_MERGE_POPUP; - window.removeTooltip = TOOLTIP_REMOVE_ANIMATION; - window.defaultTooltip = TOOLTIP_SET_DEFAULT_ANIMATION; - window.renameEdit = SNAPSHOT_RENAME_ANIMATION; - window.pasteEdit = EDIT_PASTE_ANIMATIONS; - window.deserializeFailedToast = TOAST_DESERIALIZE_ANIMATIONS_FAILED; - window.flags = WINDOW_ADD | WINDOW_DUPLICATE | WINDOW_MERGE | WINDOW_GROUP | WINDOW_REMOVE | WINDOW_DEFAULT | - WINDOW_CUT | WINDOW_COPY | WINDOW_PASTE | WINDOW_RENAME; - window.popup = PopupHelper(LABEL_ANIMATIONS_MERGE_POPUP); - window.storage_get = [](Document& document) -> Storage& { return document.animation; }; - window.element_get = [](Anm2& anm2, int index) { return anm2.element_get(ElementType::ANIMATION, index); }; - window.element_key_get = [](const Element&, int index) { return index; }; - window.row_font_get = [](Document& document, const Element& animation, int index) - { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - auto isDefault = animations && animations->defaultAnimation == animation.name; - auto isReferenced = document.reference.animationIndex == index; - return isDefault && isReferenced ? resource::font::BOLD_ITALICS - : isDefault ? resource::font::BOLD - : isReferenced ? resource::font::ITALICS - : resource::font::REGULAR; - }; - window.row_select = [](Window&, Document& document, int index) - { - document.reference = {index}; - document.frames.clear(); - }; - window.rename_finish = [](Document& document, Element& animation, int, int count) - { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - if (animations && count == 1) animations->defaultAnimation = animation.name; - }; - window.tooltip_draw = [](Document& document, Resources& resources, const Element& animation) - { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - auto isDefault = animations && animations->defaultAnimation == animation.name; - - ImGui::PushFont(resources.fonts[resource::font::BOLD].get(), resource::font::SIZE); - ImGui::TextUnformatted(animation.name.c_str()); - ImGui::PopFont(); - - if (isDefault) - { - ImGui::PushFont(resources.fonts[resource::font::ITALICS].get(), resource::font::SIZE); - ImGui::TextUnformatted(localize.get(BASIC_DEFAULT)); - ImGui::PopFont(); - } - - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_LENGTH), std::make_format_args(animation.frameNum)).c_str()); - auto loopLabel = animation.isLoop ? localize.get(BASIC_YES) : localize.get(BASIC_NO); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_LOOP), std::make_format_args(loopLabel)).c_str()); - }; - window.row_drag_drop_update = [](Window& window, Manager& manager, Document& document, const Element&, int index) - { - auto& anm2 = document.anm2; - - window_animation_drag_drop_source_update(document, window, {AnimationDragDropType::ANIMATION, index}); - - if (ImGui::BeginDragDropTarget()) - { - 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 itemMin = ImGui::GetItemRectMin(); - auto itemMax = ImGui::GetItemRectMax(); - auto isDropAfter = is_drop_after(itemMin, itemMax); - drop_line_draw(ImGui::GetWindowDrawList(), itemMin, itemMax, isDropAfter); - - if (payload->IsDelivery()) - { - auto targetIndex = index + (isDropAfter ? 1 : 0); - auto targetGroupId = -1; - if (auto targetAnimation = anm2.element_get(ElementType::ANIMATION, index)) - targetGroupId = targetAnimation->groupId; - 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; - } - } - ImGui::EndDragDropTarget(); - } - - return false; - }; - window.rows_update = - [](Window& window, Manager& manager, Settings&, Resources& resources, Clipboard&, Document& document, ImVec2) - { - auto container = window_container_get(window, document.anm2); - auto& storage = window.storage_get(document); - auto& selection = storage.selection; - auto& groupSelection = window.selection; - auto count = window_element_count_get(window, container); - auto groupIds = container ? window_animation_group_ids_get(*container) : std::set{}; - std::erase_if(groupSelection, [&](int groupId) { return !groupIds.contains(groupId); }); - std::vector visibleIds{}; - int visibleIndex{}; - - auto visible_group_children_push = [&](int groupId) - { - int animationIndex{}; - for (auto& child : container->children) - { - if (child.type != ElementType::ANIMATION) continue; - if (child.groupId == groupId) visibleIds.push_back(animationIndex); - ++animationIndex; - } - }; - - if (container) - for (auto& child : container->children) - { - if (child.type == ElementType::GROUP) - { - if (child.isExpanded) visible_group_children_push(child.id); - } - else if (child.type == ElementType::ANIMATION) - { - if (!is_window_animation_grouped(groupIds, child)) visibleIds.push_back(visibleIndex); - ++visibleIndex; - } - } - - int scrollTargetId = -1; - int arrowSelectionId = -1; - - selection.start(count); - if (container && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) - { - selection.clear(); - for (int i = 0; i < count; ++i) - selection.insert(i); - groupSelection = groupIds; - } - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && - (ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) - { - auto nextId = window_arrow_selection_get(visibleIds, storage.reference, selection); - if (nextId != -1) - { - arrowSelectionId = nextId; - scrollTargetId = nextId; - } - } - - auto animation_row_draw = [&](Element& element, int key) - { - auto isSelected = selection.contains(key) || arrowSelectionId == key; - auto font = window.row_font_get ? window.row_font_get(document, element, key) : resource::font::REGULAR; - auto isFontPushed = font != resource::font::REGULAR; - - ImGui::PushID(key); - ImGui::SetNextItemSelectionUserData(key); - auto label = window.row_label_get ? window.row_label_get(document, element) : element.name; - if (isFontPushed) ImGui::PushFont(resources.fonts[font].get(), resource::font::SIZE); - if (scrollTargetId == key) ImGui::SetKeyboardFocusHere(); - - if (window_flag_has(window.flags, WINDOW_RENAME)) - { - if (window.newElementId == key || window.renameQueued == key) - { - window.renameState = RENAME_FORCE_EDIT; - window.renameQueued = -1; - } - - auto isRenaming = window.renameId == key; - auto& name = isRenaming ? window.renameText : element.name; - bool isActivated{}; - if (selectable_input_text(label, window_rename_format_get(window, manager, key), name, isSelected, - ImGuiSelectableFlags_None, window.renameState)) - { - isActivated = true; - if (window.renameState == RENAME_BEGIN) - { - window.renameId = key; - window.renameText = element.name; - } - else if (window.renameState == RENAME_FINISHED) - { - if (isRenaming) window_rename_finish(window, manager, key, count, window.renameText); - window.renameId = -1; - window.renameText.clear(); - } - } - auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); - if (isActivated || isClicked) - { - auto& io = ImGui::GetIO(); - if (!io.KeyCtrl && !io.KeyShift) groupSelection.clear(); - storage.reference = key; - if (window.row_select) window.row_select(window, document, key); - } - } - else - { - auto isActivated = ImGui::Selectable(label.c_str(), isSelected); - auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); - if (isActivated || isClicked) - { - auto& io = ImGui::GetIO(); - if (!io.KeyCtrl && !io.KeyShift) groupSelection.clear(); - storage.reference = key; - if (window.row_select) window.row_select(window, document, key); - } - } - - if (isFontPushed) ImGui::PopFont(); - - if ((window.newElementId == key || window.scrollQueued == key || scrollTargetId == key) && - !is_drag_drop_active()) - { - ImGui::SetScrollHereY(0.5f); - if (window.newElementId == key) window.newElementId = -1; - if (window.scrollQueued == key) window.scrollQueued = -1; - } - - bool isBreak{}; - if (window.row_drag_drop_update && window.row_drag_drop_update(window, manager, document, element, key)) - isBreak = true; - - if (window.tooltip_draw) - { - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); - if (ImGui::BeginItemTooltip()) - { - window.tooltip_draw(document, resources, element); - ImGui::EndTooltip(); - } - ImGui::PopStyleVar(2); - } - - ImGui::PopID(); - return isBreak; - }; - - auto group_reference_clear = [&]() - { - storage.reference = -1; - document.reference = {}; - document.frames.clear(); - }; - - auto group_selection_apply = [&](int groupId) - { - auto& io = ImGui::GetIO(); - auto isSelected = groupSelection.contains(groupId); - if (!io.KeyCtrl) - { - selection.clear(); - groupSelection.clear(); - } - - if (io.KeyCtrl && isSelected) - { - groupSelection.erase(groupId); - if (selection.empty() && groupSelection.empty()) group_reference_clear(); - return; - } - - groupSelection.insert(groupId); - if (!io.KeyCtrl || selection.empty()) group_reference_clear(); - }; - - bool isRowsDone{}; - if (container) - { - int animationIndex{}; - for (auto& item : container->children) - { - if (item.type == ElementType::GROUP) - { - ImGui::PushID("Animation Group"); - ImGui::PushID(item.id); - auto label = item.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : item.name; - auto isGroupSelected = groupSelection.contains(item.id); - auto renameKey = window_animation_group_key_get(item.id); - auto isRenaming = window.renameId == renameKey; - auto& name = isRenaming ? window.renameText : item.name; - if (window.renameQueued == renameKey) - { - window.renameState = RENAME_FORCE_EDIT; - window.renameQueued = -1; - } - ImGui::SetNextItemOpen(item.isExpanded, ImGuiCond_Always); - auto treeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth; - auto tree = 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) - { - window.renameId = renameKey; - window.renameText = item.name; - } - else if (tree.isRenameFinished) - { - if (isRenaming && item.name != window.renameText) - { - auto targetGroupId = item.id; - auto targetName = window.renameText; - manager.command_push({manager.selected, [targetGroupId, targetName](Manager&, Document& document) - { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - auto group = animations - ? child_id_get(*animations, ElementType::GROUP, targetGroupId) - : nullptr; - if (!group || group->name == targetName) return; - document.snapshots.anm2_push(localize.get(EDIT_RENAME_GROUP)); - group->name = targetName; - document.change(Document::ANIMATIONS); - }}); - } - window.renameId = -1; - window.renameText.clear(); - } - 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) - { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - auto group = animations - ? child_id_get(*animations, ElementType::GROUP, targetGroupId) - : nullptr; - if (!group || group->isExpanded == isGroupOpen) return; - document.snapshots.anm2_push(localize.get(EDIT_TOGGLE_GROUP_EXPANDED)); - group->isExpanded = isGroupOpen; - document.change(Document::ANIMATIONS); - }}); - } - 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) - { - if (!isRowsDone) - { - 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(); - } - ImGui::PopID(); - ImGui::PopID(); - if (isRowsDone) break; - } - else if (item.type == ElementType::ANIMATION) - { - if (!is_window_animation_grouped(groupIds, item)) - if (animation_row_draw(item, animationIndex)) - { - isRowsDone = true; - break; - } - ++animationIndex; - } - } - } - - selection.finish(); - if (arrowSelectionId != -1) - { - groupSelection.clear(); - selection = {arrowSelectionId}; - storage.reference = arrowSelectionId; - if (window.row_select) window.row_select(window, document, arrowSelectionId); - } - }; - window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& anm2 = document.anm2; - auto& reference = document.reference; - auto& selection = document.animation.selection; - - auto animations = [&]() { return anm2.element_get(ElementType::ANIMATIONS); }; - auto animation_count = [&]() { return window_element_count_get(window, animations()); }; - - auto behavior = [&]() - { - auto items = animations(); - if (!items) return; - auto groupIds = window_animation_group_ids_get(*items); - auto targetGroupId = window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) - ? *window.selection.begin() - : -1; - - auto animation = element_make(ElementType::ANIMATION); - animation.name = localize.get(TEXT_NEW_ANIMATION); - animation.frameNum = 1; - animation.isLoop = true; - - auto rootAnimation = element_make(ElementType::ROOT_ANIMATION); - rootAnimation.children.push_back(element_make(ElementType::FRAME)); - animation.children.push_back(rootAnimation); - - const Element* referenceLayerAnimations{}; - const Element* referenceNullAnimations{}; - if (auto referenceAnimation = anm2.element_get(ElementType::ANIMATION, reference.animationIndex)) - { - referenceLayerAnimations = child_first_get(*referenceAnimation, ElementType::LAYER_ANIMATIONS); - referenceNullAnimations = child_first_get(*referenceAnimation, ElementType::NULL_ANIMATIONS); - } - - animation.children.push_back(window_track_container_shell_copy( - referenceLayerAnimations, ElementType::LAYER_ANIMATIONS, ElementType::LAYER_ANIMATION)); - animation.children.push_back(window_track_container_shell_copy( - referenceNullAnimations, ElementType::NULL_ANIMATIONS, ElementType::NULL_ANIMATION)); - animation.children.push_back(element_make(ElementType::TRIGGERS)); - - auto count = animation_count(); - auto index = count; - if (!selection.empty()) - index = std::min(*selection.rbegin() + 1, count); - else if (targetGroupId != -1) - { - auto groupIndices = window_animation_group_indices_get(*items, targetGroupId); - if (!groupIndices.empty()) index = std::min(*groupIndices.rbegin() + 1, count); - } - if (!selection.empty()) - if (auto selectedAnimation = anm2.element_get(ElementType::ANIMATION, *selection.rbegin())) - { - if (groupIds.contains(selectedAnimation->groupId)) animation.groupId = selectedAnimation->groupId; - } - if (selection.empty() && targetGroupId != -1) animation.groupId = targetGroupId; - if (count == 0) items->defaultAnimation = animation.name; - - auto childIndex = window_animation_child_insert_index_get(*items, index); - items->children.insert(items->children.begin() + childIndex, animation); - selection = {index}; - window.selection.clear(); - reference = {index}; - window.newElementId = index; - window.scrollQueued = index; - }; - - window_edit(window, document, localize.get(EDIT_ADD_ANIMATION), behavior); - }; - window.remove = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& selection = document.animation.selection; - auto& reference = document.reference; - auto& overlayIndex = document.overlayIndex; - auto& overlayDocumentId = document.overlayDocumentId; - auto groupSelection = window.selection; - - auto behavior = [&]() - { - auto items = document.anm2.element_get(ElementType::ANIMATIONS); - if (!items || (selection.empty() && groupSelection.empty())) return; - if (!groupSelection.empty()) - { - for (auto& item : items->children) - if (item.type == ElementType::ANIMATION && groupSelection.contains(item.groupId)) item.groupId = -1; - std::erase_if(items->children, [&](const Element& item) - { return item.type == ElementType::GROUP && groupSelection.contains(item.id); }); - } - for (auto it = selection.rbegin(); it != selection.rend(); ++it) - { - auto i = *it; - auto childIndex = window_animation_child_index_get(*items, i); - if (childIndex == -1) continue; - if ((overlayDocumentId == 0 || overlayDocumentId == document.tabId) && overlayIndex == i) - { - overlayIndex = -1; - overlayDocumentId = 0; - } - if (reference.animationIndex == i) reference.animationIndex = -1; - items->children.erase(items->children.begin() + childIndex); - } - selection.clear(); - window.selection.clear(); - }; - - auto edit = groupSelection.empty() ? EDIT_REMOVE_ANIMATIONS : EDIT_REMOVE_GROUP; - window_edit(window, document, localize.get(edit), behavior); - }; - window.duplicate = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& selection = document.animation.selection; - - auto behavior = [&]() - { - auto items = document.anm2.element_get(ElementType::ANIMATIONS); - auto clipboardText = window_animation_clipboard_text_get(document, window); - if (!items || clipboardText.empty()) return; - - auto selectedIndices = window_animation_selected_indices_get(document, window); - auto count = window_element_count_get(window, items); - auto start = selectedIndices.empty() ? count : std::min(*selectedIndices.rbegin() + 1, count); - std::set indices{}; - std::set groupIds{}; - std::string errorString{}; - if (!document.anm2.animations_deserialize(clipboardText, start, indices, &errorString, &groupIds)) return; - - if (!groupIds.empty()) - { - selection.clear(); - window.selection = groupIds; - document.reference = {}; - window.newElementId = -1; - } - else - { - selection = indices; - window.selection.clear(); - } - if (!indices.empty() && groupIds.empty()) - { - auto index = *indices.rbegin(); - document.reference = {index}; - window.newElementId = indices.size() == 1 && groupIds.empty() ? index : -1; - window.scrollQueued = index; - } - else if (!indices.empty()) - window.scrollQueued = *indices.rbegin(); - }; - - window_edit(window, document, localize.get(EDIT_DUPLICATE_ANIMATIONS), behavior); - }; - window.merge = [](Window& window, Manager&, Settings& settings, Document& document, Clipboard&) - { - auto& mergeSelection = document.merge.selection; - auto& mergeReference = document.merge.reference; - auto quickSelection = - mergeSelection.empty() ? window_animation_selected_indices_get(document, window) : std::set{}; - auto quickGroupSelection = mergeSelection.empty() ? window.selection : std::set{}; - auto merged = window_animations_merge(document, - {.selection = mergeSelection, - .reference = mergeReference, - .type = (merge::Type)settings.mergeType, - .isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter}, - mergeSelection.empty() ? &quickSelection : nullptr, - mergeSelection.empty() ? &quickGroupSelection : nullptr); - if (merged != -1) - { - window.scrollQueued = merged; - window.selection.clear(); - } - mergeSelection.clear(); - }; - window.merge_open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& selection = document.animation.selection; - if (selection.empty()) return; - window.popup.open(); - document.merge.selection.clear(); - document.merge.reference = *selection.begin(); - }; - window.group = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto targetIndices = window_animation_groupable_indices_get(document); - if (targetIndices.empty()) return; - - auto behavior = [&]() - { - auto items = document.anm2.element_get(ElementType::ANIMATIONS); - if (!items) return; - - std::set targetSet(targetIndices.begin(), targetIndices.end()); - auto group = element_make(ElementType::GROUP); - group.id = element_child_next_id_get(*items, ElementType::GROUP); - group.name = localize.get(TEXT_NEW_GROUP); - group.isExpanded = true; - int insertIndex = (int)items->children.size(); - int animationIndex{}; - - for (int i = 0; i < (int)items->children.size(); ++i) - { - auto& item = items->children[i]; - if (item.type != ElementType::ANIMATION) continue; - if (targetSet.contains(animationIndex)) - { - insertIndex = std::min(insertIndex, i); - item.groupId = group.id; - } - ++animationIndex; - } - - if (insertIndex == (int)items->children.size()) return; - items->children.insert(items->children.begin() + insertIndex, group); - document.animation.selection = targetSet; - window.selection = {group.id}; - document.reference = {*targetSet.begin()}; - window.scrollQueued = *targetSet.begin(); - }; - - window_edit(window, document, localize.get(EDIT_GROUP_ITEMS), behavior); - }; - window.default_set = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& selection = document.animation.selection; - - auto behavior = [&]() - { - auto items = document.anm2.element_get(ElementType::ANIMATIONS); - auto animation = document.anm2.element_get(ElementType::ANIMATION, *selection.begin()); - if (!items || !animation) return; - items->defaultAnimation = animation->name; - }; - - window_edit(window, document, localize.get(EDIT_DEFAULT_ANIMATION), behavior); - }; - window.copy = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) - { - auto clipboardText = window_animation_clipboard_text_get(document, window); - if (!clipboardText.empty()) clipboard.set(clipboardText); - }; - window.cut = [](Window& window, Manager& manager, Settings& settings, Document& document, Clipboard& clipboard) - { - if (window.copy) window.copy(window, manager, settings, document, clipboard); - - auto& selection = document.animation.selection; - auto groupSelection = window.selection; - auto selectedIndices = window_animation_selected_indices_get(document, window); - auto behavior = [&]() - { - auto items = document.anm2.element_get(ElementType::ANIMATIONS); - if (!items) return; - for (auto it = selectedIndices.rbegin(); it != selectedIndices.rend(); ++it) - { - auto i = *it; - auto childIndex = window_animation_child_index_get(*items, i); - if (childIndex == -1) continue; - if ((document.overlayDocumentId == 0 || document.overlayDocumentId == document.tabId) && - document.overlayIndex == i) - { - document.overlayIndex = -1; - document.overlayDocumentId = 0; - } - if (document.reference.animationIndex == i) document.reference.animationIndex = -1; - items->children.erase(items->children.begin() + childIndex); - } - std::erase_if(items->children, [&](const Element& item) - { return item.type == ElementType::GROUP && groupSelection.contains(item.id); }); - selection.clear(); - window.selection.clear(); - }; - - window_edit(window, document, localize.get(EDIT_CUT_ANIMATIONS), behavior); - }; - window.paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) - { - if (clipboard.is_empty()) return; - - auto& anm2 = document.anm2; - auto& selection = document.animation.selection; - auto& reference = document.reference; - auto animation_count = [&]() - { return window_element_count_get(window, anm2.element_get(ElementType::ANIMATIONS)); }; - - auto behavior = [&]() - { - auto clipboardText = clipboard.get(); - auto start = selection.empty() ? animation_count() : *selection.rbegin() + 1; - auto items = anm2.element_get(ElementType::ANIMATIONS); - auto groupIdsBefore = items ? window_animation_group_ids_get(*items) : std::set{}; - auto targetGroupId = - selection.empty() && window.selection.size() == 1 && groupIdsBefore.contains(*window.selection.begin()) - ? *window.selection.begin() - : -1; - if (selection.empty() && targetGroupId != -1) - { - auto groupIndices = window_animation_group_indices_get(*items, targetGroupId); - if (!groupIndices.empty()) start = std::min(*groupIndices.rbegin() + 1, animation_count()); - } - std::set indices{}; - std::set groupIds{}; - std::string errorString{}; - if (anm2.animations_deserialize(clipboardText, start, indices, &errorString, &groupIds)) - { - if (targetGroupId != -1 && groupIds.empty()) - for (auto index : indices) - if (auto animation = anm2.element_get(ElementType::ANIMATION, index)) animation->groupId = targetGroupId; - - if (!groupIds.empty()) - { - selection.clear(); - window.selection = groupIds; - reference = {}; - window.newElementId = -1; - } - else if (!indices.empty()) - { - auto index = *indices.rbegin(); - selection = {index}; - window.selection.clear(); - reference = {index}; - window.newElementId = indices.size() == 1 ? index : -1; - window.scrollQueued = index; - } - if (!indices.empty()) window.scrollQueued = *indices.rbegin(); - } - else - { - toast_log(Level::ERROR, TOAST_DESERIALIZE_ANIMATIONS_FAILED, errorString); - } - }; - - window_edit(window, document, localize.get(EDIT_PASTE_ANIMATIONS), behavior); - }; - window.begin_update = [](Window&, Manager&, Settings&, Resources&, Clipboard&, Document& document) - { - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && ImGui::IsKeyPressed(ImGuiKey_Escape)) - document.reference = {}; - }; - window.body_update = - [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard&, Document& document) - { - auto animations = [&]() { return document.anm2.element_get(ElementType::ANIMATIONS); }; - auto& mergeSelection = document.merge.selection; - auto& mergeReference = document.merge.reference; - - window.popup.trigger(); - - if (ImGui::BeginPopupModal(window.popup.label(), &window.popup.isOpen, ImGuiWindowFlags_NoResize)) - { - auto close = [&]() - { - mergeSelection.clear(); - window.popup.close(); - }; - - auto& type = settings.mergeType; - auto& isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter; - struct AnimationMergeCandidate - { - int key{}; - std::string label{}; - }; - std::vector candidates{}; - auto items = animations(); - auto groupIds = items ? window_animation_group_ids_get(*items) : std::set{}; - - if (items) - { - auto candidate_animation_push = [&](const Element& animation, int animationIndex, bool isGrouped) - { - if (animationIndex == mergeReference) return; - auto label = isGrouped ? std::format(" {}", animation.name) : animation.name; - candidates.push_back({.key = animationIndex, .label = label}); - }; - - int animationIndex{}; - for (const auto& item : items->children) - { - if (item.type == ElementType::GROUP) - { - auto groupIndices = window_animation_group_indices_get(*items, item.id); - groupIndices.erase(mergeReference); - if (!groupIndices.empty()) - { - auto label = item.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : item.name; - candidates.push_back({.key = window_animation_group_key_get(item.id), .label = label}); - int groupAnimationIndex{}; - for (const auto& animation : items->children) - { - if (animation.type != ElementType::ANIMATION) continue; - if (animation.groupId == item.id) candidate_animation_push(animation, groupAnimationIndex, true); - ++groupAnimationIndex; - } - } - } - else if (item.type == ElementType::ANIMATION) - { - if (!is_window_animation_grouped(groupIds, item)) candidate_animation_push(item, animationIndex, false); - ++animationIndex; - } - } - } - - auto footerSize = footer_size_get(); - auto optionsSize = child_size_get(2); - auto deleteAfterSize = child_size_get(); - auto animationsSize = - ImVec2(0, ImGui::GetContentRegionAvail().y - - (optionsSize.y + deleteAfterSize.y + footerSize.y + ImGui::GetStyle().ItemSpacing.y * 3)); - - if (ImGui::BeginChild(localize.get(LABEL_ANIMATIONS_CHILD), animationsSize, ImGuiChildFlags_Borders)) - { - std::vector candidateKeys{}; - candidateKeys.reserve(candidates.size()); - for (const auto& candidate : candidates) - candidateKeys.push_back(candidate.key); - - mergeSelection.set_index_map(&candidateKeys); - mergeSelection.start(candidates.size()); - - for (int i = 0; i < (int)candidates.size(); ++i) - { - const auto& candidate = candidates[i]; - ImGui::PushID(candidate.key); - ImGui::SetNextItemSelectionUserData(i); - ImGui::Selectable(candidate.label.c_str(), mergeSelection.contains(candidate.key)); - ImGui::PopID(); - } - - mergeSelection.finish(); - mergeSelection.set_index_map(nullptr); - } - ImGui::EndChild(); - - if (ImGui::BeginChild("##Merge Options", optionsSize, ImGuiChildFlags_Borders)) - { - auto size = ImVec2(optionsSize.x * 0.5f, optionsSize.y - ImGui::GetStyle().WindowPadding.y * 2); - - if (ImGui::BeginChild("##Merge Options 1", size)) - { - ImGui::RadioButton(localize.get(LABEL_APPEND_FRAMES), &type, merge::APPEND); - ImGui::RadioButton(localize.get(LABEL_PREPEND_FRAMES), &type, merge::PREPEND); - } - ImGui::EndChild(); - - ImGui::SameLine(); - - if (ImGui::BeginChild("##Merge Options 2", size)) - { - ImGui::RadioButton(localize.get(LABEL_REPLACE_FRAMES), &type, merge::REPLACE); - ImGui::RadioButton(localize.get(LABEL_IGNORE_FRAMES), &type, merge::IGNORE); - } - ImGui::EndChild(); - } - ImGui::EndChild(); - - if (ImGui::BeginChild("##Merge Delete After", deleteAfterSize, ImGuiChildFlags_Borders)) - ImGui::Checkbox(localize.get(LABEL_DELETE_ANIMATIONS_AFTER), &isDeleteAnimationsAfter); - ImGui::EndChild(); - - auto widgetSize = widget_size_with_row_get(2); - - ImGui::BeginDisabled(window_animation_merge_indices_get(document, mergeSelection, mergeReference).empty()); - if (ImGui::Button(localize.get(LABEL_MERGE), widgetSize)) - { - auto queuedSelection = mergeSelection; - auto queuedReference = mergeReference; - AnimationMergeOptions options{.selection = queuedSelection, - .reference = queuedReference, - .type = (merge::Type)type, - .isDeleteAnimationsAfter = isDeleteAnimationsAfter}; - manager.command_push({manager.selected, [options](Manager&, Document& document) mutable - { window_animations_merge(document, options); }}); - close(); - } - ImGui::EndDisabled(); - - ImGui::SameLine(); - if (ImGui::Button(localize.get(LABEL_CLOSE), widgetSize)) close(); - - ImGui::EndPopup(); - } - }; - window.post_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) - { - auto isNextAnimation = shortcut(manager.chords[SHORTCUT_NEXT_ANIMATION], shortcut::GLOBAL); - auto isPreviousAnimation = shortcut(manager.chords[SHORTCUT_PREVIOUS_ANIMATION], shortcut::GLOBAL); - auto count = window_element_count_get(window, window_container_get(window, document.anm2)); - - if ((isPreviousAnimation || isNextAnimation) && count > 0) - { - auto& reference = document.reference; - if (isPreviousAnimation) reference.animationIndex = std::clamp(reference.animationIndex - 1, 0, count - 1); - if (isNextAnimation) reference.animationIndex = std::clamp(reference.animationIndex + 1, 0, count - 1); - - window.storage_get(document).selection = {reference.animationIndex}; - window.scrollQueued = reference.animationIndex; - } - }; - return window; - } - - Window regions_window_register() - { - Window window{}; - window.title = LABEL_REGIONS_WINDOW; - window.isOpen = &Settings::windowIsRegions; - window.changeType = Document::SPRITESHEETS; - window.elementType = ElementType::REGION; - window.childLabel = "##Regions Child"; - window.footerRows = 1; - window.flags = 0; - window.isChildPaddingZero = true; - 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); }; - window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - document.region.reference = -1; - window.editElement = element_make(ElementType::REGION); - window.popup.open(); - }; - window.properties = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& reference = document.region.reference; - auto& selection = document.region.selection; - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, document.spritesheet.reference); - if (!spritesheet || selection.size() != 1) return; - auto id = *selection.begin(); - if (!child_id_get(*spritesheet, ElementType::REGION, id)) return; - reference = id; - window.popup.open(); - }; - window.remove = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& anm2 = document.anm2; - auto spritesheetReference = document.spritesheet.reference; - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetReference); - if (!spritesheet) return; - - auto unused = anm2.region_unused(spritesheetReference); - if (unused.empty()) return; - - auto behavior = [&]() - { - auto target = anm2.element_get(ElementType::SPRITESHEET, spritesheetReference); - if (!target) return; - for (auto& id : unused) - { - if (auto animations = anm2.element_get(ElementType::ANIMATIONS)) - for (auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); - if (!layerAnimations) continue; - auto region_clear = [&](auto&& self, Element& layerAnimation) -> void - { - if (layerAnimation.type == ElementType::GROUP) - { - for (auto& child : layerAnimation.children) - self(self, child); - return; - } - if (layerAnimation.type != ElementType::LAYER_ANIMATION) return; - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, layerAnimation.layerId); - if (!layer || layer->spritesheetId != spritesheetReference) return; - for (auto& frame : layerAnimation.children) - if (frame.type == ElementType::FRAME && frame.regionId == id) frame.regionId = -1; - }; - for (auto& layerAnimation : layerAnimations->children) - region_clear(region_clear, layerAnimation); - } - - element_child_id_erase(*target, ElementType::REGION, id); - } - }; - - window_edit(window, document, localize.get(EDIT_REMOVE_UNUSED_REGIONS), behavior); - }; - window.trim = [](Window&, Manager&, Settings&, Document& document, Clipboard&) - { - auto& selection = document.region.selection; - auto& reference = document.region.reference; - auto& frame = document.frames; - auto spritesheetReference = document.spritesheet.reference; - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, spritesheetReference); - if (!spritesheet || selection.empty()) return; - - auto behavior = [&]() - { - if (document.regions_trim(spritesheetReference, selection)) - { - if (reference != -1 && !selection.contains(reference)) reference = *selection.begin(); - document.reference = {document.reference.animationIndex}; - frame.reference = -1; - frame.selection.clear(); - } - }; - - document.snapshots.anm2_push(localize.get(EDIT_TRIM_REGIONS)); - behavior(); - document.change(Document::SPRITESHEETS); - }; - window.copy = [](Window&, Manager&, Settings&, Document& document, Clipboard& clipboard) - { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, document.spritesheet.reference); - auto& selection = document.region.selection; - if (!spritesheet || selection.empty()) return; - - std::string clipboardText{}; - for (auto& region : spritesheet->children) - if (region.type == ElementType::REGION && selection.contains(region.id)) - clipboardText += element_to_string(region); - clipboard.set(clipboardText); - }; - window.paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) - { - auto spritesheetReference = document.spritesheet.reference; - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, spritesheetReference); - if (!spritesheet || clipboard.is_empty()) return; - - auto& anm2 = document.anm2; - auto& selection = document.region.selection; - auto& reference = document.region.reference; - auto maxRegionIdBefore = element_child_max_id_get(*spritesheet, ElementType::REGION); - auto insertIndex = region_insert_index_get(*spritesheet, document.region); - auto pasted = anm2; - std::string errorString{}; - if (pasted.deserialize(ElementType::REGION, clipboard.get(), true, &errorString, {}, spritesheetReference)) - { - document.snapshots.anm2_push(localize.get(EDIT_PASTE_REGIONS)); - anm2 = std::move(pasted); - if (auto pastedSpritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetReference)) - { - auto maxRegionIdAfter = element_child_max_id_get(*pastedSpritesheet, ElementType::REGION); - if (maxRegionIdAfter > maxRegionIdBefore) - { - std::vector pastedIndices{}; - for (int i = 0; i < (int)pastedSpritesheet->children.size(); i++) - if (pastedSpritesheet->children[i].type == ElementType::REGION && - pastedSpritesheet->children[i].id > maxRegionIdBefore) - pastedIndices.push_back(i); - vector::move_indices_to_position(pastedSpritesheet->children, pastedIndices, insertIndex); - window.newElementId = maxRegionIdAfter; - selection = {maxRegionIdAfter}; - reference = maxRegionIdAfter; - } - } - document.change(Document::SPRITESHEETS); - } - else - { - toast_log(Level::ERROR, TOAST_DESERIALIZE_REGIONS_FAILED, errorString); - } - }; - window.begin_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) - { - if (!manager.isMakeRegionRequested) return; - document.spritesheet.reference = manager.makeRegionSpritesheetId; - document.region.reference = -1; - window.editElement = manager.makeRegion; - window.isPreserveEditElementOnOpen = true; - window.popup.open(); - manager.isMakeRegionRequested = false; - }; - window.rows_update = [](Window& window, Manager& manager, Settings& settings, Resources& resources, - Clipboard& clipboard, Document& document, ImVec2) - { - auto& anm2 = document.anm2; - auto& selection = document.region.selection; - auto& frame = document.frames; - auto& spritesheetReference = document.spritesheet.reference; - auto& reference = document.region.reference; - auto style = ImGui::GetStyle(); - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetReference); - if (!spritesheet) - { - ImGui::TextUnformatted(localize.get(TEXT_SELECT_SPRITESHEET)); - return; - } - - auto regionChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 2); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); - - window.order.clear(); - window.order.reserve(spritesheet->children.size()); - for (auto& region : spritesheet->children) - if (region.type == ElementType::REGION) window.order.push_back(region.id); - - selection.set_index_map(&window.order); - selection.start(window.order.size()); - if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) - { - selection.clear(); - for (auto& id : window.order) - selection.insert(id); - } - if (ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) - { - selection.clear(); - reference = -1; - document.reference = {document.reference.animationIndex}; - frame.reference = -1; - frame.selection.clear(); - } - - int scrollTargetId = -1; - int arrowSelectionId = -1; - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && - (ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) - { - auto nextId = window_arrow_selection_get(window.order, reference, selection); - if (nextId != -1) - { - arrowSelectionId = nextId; - scrollTargetId = nextId; - } - } - - auto textureInfo = document.texture_get(spritesheetReference); - bool isValid = textureInfo && textureInfo->is_valid(); - auto& texture = isValid ? *textureInfo : resources.icons[icon::NONE]; - auto tintColor = !isValid ? ImVec4(1.0f, 0.25f, 0.25f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - bool isRegionDragDropSourceSubmitted{}; - bool isRegionMoved{}; - - for (int i = 0; i < (int)window.order.size(); i++) - { - int id = window.order[i]; - auto region = child_id_get(*spritesheet, ElementType::REGION, id); - if (!region) continue; - auto isNewRegion = window.newElementId == id; - auto nameCStr = region->name.c_str(); - auto isSelected = selection.contains(id) || arrowSelectionId == id; - auto isReferenced = id == reference || arrowSelectionId == id; - - ImGui::PushID(id); - - window_scroll_to_item(regionChildSize.y, scrollTargetId == id); - if (scrollTargetId == id) ImGui::SetNextWindowFocus(); - - if (ImGui::BeginChild("##Region Child", regionChildSize, ImGuiChildFlags_Borders)) - { - auto cursorPos = ImGui::GetCursorPos(); - auto regionChildMin = ImGui::GetWindowPos(); - auto regionChildMax = - ImVec2(regionChildMin.x + ImGui::GetWindowSize().x, regionChildMin.y + ImGui::GetWindowSize().y); - - ImGui::SetNextItemSelectionUserData(i); - ImGui::SetNextItemStorageID(id); - if (scrollTargetId == id) ImGui::SetKeyboardFocusHere(); - auto isActivated = ImGui::Selectable("##Region Selectable", isSelected, 0, regionChildSize); - auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); - if (isActivated || isClicked) - { - document.editTarget = Document::EditTarget::REGION; - reference = id; - document.reference = {document.reference.animationIndex}; - frame.reference = -1; - frame.selection.clear(); - } - auto regionRowMin = ImGui::GetItemRectMin(); - auto regionRowMax = ImGui::GetItemRectMax(); - if (scrollTargetId == id) ImGui::SetItemDefaultFocus(); - if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) window.popup.open(); - - auto viewport = ImGui::GetMainViewport(); - auto maxPreviewSize = to_vec2(viewport->Size) * 0.5f; - vec2 regionSize = glm::max(region->size, vec2(1.0f)); - vec2 previewSize = regionSize; - if (previewSize.x > maxPreviewSize.x || previewSize.y > maxPreviewSize.y) - { - auto scale = glm::min(maxPreviewSize.x / previewSize.x, maxPreviewSize.y / previewSize.y); - previewSize *= scale; - } - vec2 uvMin{}; - vec2 uvMax{1.0f, 1.0f}; - if (isValid) - { - uvMin = region->crop / vec2(texture.size); - uvMax = (region->crop + region->size) / vec2(texture.size); - } - - auto textWidth = ImGui::CalcTextSize(nameCStr).x; - auto tooltipPadding = window.tooltipWindowPadding.x * 4.0f; - auto minWidth = previewSize.x + window.tooltipItemSpacing.x + textWidth + tooltipPadding; - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip) && !ImGui::IsMouseDragging(ImGuiMouseButton_Left)) - { - ImGui::SetNextWindowSize(ImVec2(minWidth, 0), ImGuiCond_Appearing); - if (ImGui::BeginItemTooltip()) - { - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - auto childFlags = ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY; - auto noScrollFlags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; - - if (ImGui::BeginChild("##Region Tooltip Image Child", to_imvec2(previewSize), childFlags, noScrollFlags)) - ImGui::ImageWithBg(texture.id, to_imvec2(previewSize), to_imvec2(uvMin), to_imvec2(uvMax), ImVec4(), - tintColor); - ImGui::EndChild(); - ImGui::PopStyleVar(); - - ImGui::SameLine(); - - auto infoChildFlags = ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY; - if (ImGui::BeginChild("##Region Info Tooltip Child", ImVec2(), infoChildFlags, noScrollFlags)) - { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(nameCStr); - ImGui::PopFont(); - - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_CROP), std::make_format_args(region->crop.x, region->crop.y)) - .c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_SIZE), std::make_format_args(region->size.x, region->size.y)) - .c_str()); - if (region->origin == Origin::CUSTOM) - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_PIVOT), std::make_format_args(region->pivot.x, region->pivot.y)) - .c_str()); - else - { - StringType originString = LABEL_REGION_ORIGIN_CENTER; - if (region->origin == Origin::TOP_LEFT) originString = LABEL_REGION_ORIGIN_TOP_LEFT; - auto originLabel = localize.get(originString); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_ORIGIN), std::make_format_args(originLabel)).c_str()); - } - } - ImGui::EndChild(); - ImGui::EndTooltip(); - } - } - ImGui::PopStyleVar(2); - - if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) - { - isRegionDragDropSourceSubmitted = true; - if (selection.contains(id)) - window.dragSelection.assign(selection.begin(), selection.end()); - else - window.dragSelection = {id}; - - ImGui::SetDragDropPayload("Region Drag Drop", window.dragSelection.data(), - window.dragSelection.size() * sizeof(int)); - ImGui::EndDragDropSource(); - } - - bool isDropLineActive{}; - bool isDropLineAfter{}; - if (ImGui::BeginDragDropTarget()) - { - if (auto payload = - ImGui::AcceptDragDropPayload("Region Drag Drop", ImGuiDragDropFlags_AcceptBeforeDelivery | - ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) - { - isDropLineActive = true; - isDropLineAfter = is_drop_after(regionRowMin, regionRowMax); - - auto payloadIds = (int*)(payload->Data); - int payloadCount = (int)(payload->DataSize / sizeof(int)); - std::vector indices{}; - indices.reserve(payloadCount); - for (int payloadIndex = 0; payloadIndex < payloadCount; payloadIndex++) - { - int payloadId = payloadIds[payloadIndex]; - int index = vector::find_index(window.order, payloadId); - if (index != -1) indices.push_back(index); - } - if (!indices.empty() && payload->IsDelivery()) - { - std::sort(indices.begin(), indices.end()); - auto movedIds = window.dragSelection; - auto targetIndex = i + (isDropLineAfter ? 1 : 0); - auto targetSpritesheetReference = spritesheetReference; - manager.command_push( - {manager.selected, [&window, indices, movedIds, targetIndex, - targetSpritesheetReference](Manager&, Document& document) mutable - { - auto spritesheet = - document.anm2.element_get(ElementType::SPRITESHEET, targetSpritesheetReference); - if (!spritesheet) return; - - auto move = [&]() - { - vector::move_indices_to_position(spritesheet->children, indices, targetIndex); - document.region.selection.clear(); - for (auto id : movedIds) - document.region.selection.insert(id); - }; - window_edit(window, document, localize.get(EDIT_MOVE_REGIONS), move); - }}); - isRegionMoved = true; - } - } - ImGui::EndDragDropTarget(); - } - - auto imageSize = to_imvec2(vec2(regionChildSize.y)); - auto aspectRatio = region->size.y != 0.0f ? (float)region->size.x / region->size.y : 1.0f; - - if (imageSize.x / imageSize.y > aspectRatio) - imageSize.x = imageSize.y * aspectRatio; - else - imageSize.y = imageSize.x / aspectRatio; - - ImGui::SetCursorPos(cursorPos); - ImGui::ImageWithBg(texture.id, imageSize, to_imvec2(uvMin), to_imvec2(uvMax), ImVec4(), tintColor); - - ImGui::SetCursorPos(ImVec2(regionChildSize.y + style.ItemSpacing.x, - regionChildSize.y - regionChildSize.y / 2 - ImGui::GetTextLineHeight() / 2)); - - if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); - ImGui::TextUnformatted(nameCStr); - if (isReferenced) ImGui::PopFont(); - - if (isDropLineActive) - drop_line_draw(ImGui::GetWindowDrawList(), regionChildMin, regionChildMax, isDropLineAfter); - } - - ImGui::EndChild(); - - if (isNewRegion && !is_drag_drop_active()) - { - ImGui::SetScrollHereY(0.5f); - window.newElementId = -1; - } - - ImGui::PopID(); - if (isRegionMoved) break; - } - - auto regionDragPayload = isRegionMoved ? nullptr : ImGui::GetDragDropPayload(); - bool isRegionDragActive = regionDragPayload && regionDragPayload->IsDataType("Region Drag Drop"); - if (isRegionDragActive && !isRegionDragDropSourceSubmitted && !window.dragSelection.empty() && - ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceExtern | DRAG_DROP_SOURCE_FLAGS)) - { - ImGui::SetDragDropPayload("Region Drag Drop", window.dragSelection.data(), - window.dragSelection.size() * sizeof(int)); - ImGui::EndDragDropSource(); - } - - if (isRegionDragActive && !window.dragSelection.empty()) - { - auto mousePos = ImGui::GetIO().MousePos; - auto tooltipOffset = ImVec2(16.0f, 16.0f); - ImGui::SetNextWindowPos(ImVec2(mousePos.x + tooltipOffset.x, mousePos.y + tooltipOffset.y)); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); - if (ImGui::BeginTooltip()) - { - for (auto regionId : window.dragSelection) - { - auto drag = child_id_get(*spritesheet, ElementType::REGION, regionId); - if (drag) ImGui::TextUnformatted(drag->name.c_str()); - } - ImGui::EndTooltip(); - } - ImGui::PopStyleVar(2); - } - - ImGui::PopStyleVar(); - selection.finish(); - selection.set_index_map(nullptr); - if (arrowSelectionId != -1) - { - document.editTarget = Document::EditTarget::REGION; - selection = {arrowSelectionId}; - reference = arrowSelectionId; - document.reference = {document.reference.animationIndex}; - frame.reference = -1; - frame.selection.clear(); - } - - if (shortcut(manager.chords[SHORTCUT_ADD], shortcut::FOCUSED) && window.add) - window_command_run(window, manager, settings, document, clipboard, window.add); - if (shortcut(manager.chords[SHORTCUT_REMOVE], shortcut::FOCUSED) && window.remove) - window_command_run(window, manager, settings, document, clipboard, window.remove); - if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED) && window.copy) - window_command_run(window, manager, settings, document, clipboard, window.copy); - if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED) && window.paste) - window_command_run(window, manager, settings, document, clipboard, window.paste); - if (shortcut(manager.chords[SHORTCUT_CONFIRM], shortcut::FOCUSED) && selection.size() == 1 && window.properties) - window_command_run(window, manager, settings, document, clipboard, window.properties); - }; - window.context_update = - [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard& clipboard, Document& document) - { - auto& selection = document.region.selection; - auto style = ImGui::GetStyle(); - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && - ImGui::IsMouseClicked(ImGuiMouseButton_Right)) - ImGui::OpenPopup("##Region Context Menu"); - - Actions actions{}; - actions_undo_redo_add(actions, manager, document); - actions.separator(); - actions.add( - ACTION_PROPERTIES, [&]() { return selection.size() == 1 && (bool)window.properties; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.properties); }); - actions.add( - ACTION_ADD, [&]() { return (bool)window.add; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }); - actions.add( - ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); - 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); }); - actions.add( - ACTION_PASTE, [&]() { return !clipboard.is_empty() && (bool)window.paste; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.paste); }); - actions_popup_draw("##Region Context Menu", actions, settings); - ImGui::PopStyleVar(2); - }; - window.footer_update = - [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard& clipboard, Document& document) - { - auto rowOneWidgetSize = widget_size_with_row_get(3); - - shortcut(manager.chords[SHORTCUT_ADD]); - if (ImGui::Button(localize.get(BASIC_ADD), rowOneWidgetSize) && window.add) - window_command_run(window, manager, settings, document, clipboard, window.add); - set_item_tooltip_shortcut(localize.get(TOOLTIP_ADD_REGION), settings.shortcutAdd); - - 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& settings, Resources& resources, Clipboard&, Document& document) - { - auto& anm2 = document.anm2; - auto& spritesheetReference = document.spritesheet.reference; - auto& reference = document.region.reference; - auto spritesheet_get = [&]() { return anm2.element_get(ElementType::SPRITESHEET, spritesheetReference); }; - auto region_get = [&](int id) - { - auto spritesheet = spritesheet_get(); - return spritesheet ? child_id_get(*spritesheet, ElementType::REGION, id) : nullptr; - }; - - window.popup.trigger(); - - if (ImGui::BeginPopupModal(window.popup.label(), &window.popup.isOpen, ImGuiWindowFlags_NoResize)) - { - auto spritesheet = spritesheet_get(); - auto targetRegion = reference == -1 ? nullptr : region_get(reference); - if (!spritesheet || (reference != -1 && !targetRegion)) - { - window.popup.close(); - ImGui::EndPopup(); - return; - } - - auto childSize = child_size_get(5); - - if (window.popup.isJustOpened) - { - if (!window.isPreserveEditElementOnOpen) - window.editElement = targetRegion ? *targetRegion : element_make(ElementType::REGION); - window.isPreserveEditElementOnOpen = false; - } - auto& region = window.editElement; - - if (ImGui::BeginChild("##Child", childSize, ImGuiChildFlags_Borders)) - { - const char* originOptions[] = {localize.get(LABEL_REGION_ORIGIN_TOP_LEFT), - localize.get(LABEL_REGION_ORIGIN_CENTER), - localize.get(LABEL_REGION_ORIGIN_CUSTOM)}; - - if (window.popup.isJustOpened) ImGui::SetKeyboardFocusHere(); - input_text_string(localize.get(BASIC_NAME), ®ion.name); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); - ImGui::DragFloat2(localize.get(BASIC_CROP), value_ptr(region.crop), DRAG_SPEED, 0.0f, 0.0f, - math::vec2_format_get(region.crop)); - ImGui::DragFloat2(localize.get(BASIC_SIZE), value_ptr(region.size), DRAG_SPEED, 0.0f, 0.0f, - math::vec2_format_get(region.size)); - ImGui::BeginDisabled(region.origin != Origin::CUSTOM); - ImGui::DragFloat2(localize.get(BASIC_PIVOT), value_ptr(region.pivot), DRAG_SPEED, 0.0f, 0.0f, - math::vec2_format_get(region.pivot)); - ImGui::EndDisabled(); - - int originIndex = region.origin == Origin::TOP_LEFT ? 0 : region.origin == Origin::CENTER ? 1 : 2; - if (ImGui::Combo(localize.get(LABEL_REGION_PROPERTIES_ORIGIN), &originIndex, originOptions, - IM_ARRAYSIZE(originOptions))) - { - region.origin = originIndex == 0 ? Origin::TOP_LEFT : originIndex == 1 ? Origin::CENTER : Origin::CUSTOM; - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REGION_PROPERTIES_ORIGIN)); - } - - if (region.origin == Origin::TOP_LEFT) - region.pivot = {}; - else if (region.origin == Origin::CENTER) - region.pivot = region.size * 0.5f; - } - ImGui::EndChild(); - - auto widgetSize = widget_size_with_row_get(2); - - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(reference == -1 ? localize.get(BASIC_ADD) : localize.get(BASIC_CONFIRM), widgetSize)) - { - auto editedRegion = region; - auto editedReference = reference; - auto editedSpritesheetReference = spritesheetReference; - manager.command_push({manager.selected, [&window, editedRegion, editedReference, - editedSpritesheetReference](Manager&, Document& document) mutable - { - auto spritesheet = - document.anm2.element_get(ElementType::SPRITESHEET, editedSpritesheetReference); - if (!spritesheet) return; - - auto& selection = document.region.selection; - auto& reference = document.region.reference; - auto& frame = document.frames; - - if (editedReference == -1) - { - auto add = [&]() - { - auto added = editedRegion; - auto id = element_child_next_id_get(*spritesheet, ElementType::REGION); - added.type = ElementType::REGION; - added.tag = "Region"; - added.id = id; - auto insertIndex = region_insert_index_get(*spritesheet, document.region); - spritesheet->children.insert(spritesheet->children.begin() + insertIndex, added); - selection = {id}; - reference = id; - window.newElementId = id; - }; - - window_edit(window, document, localize.get(EDIT_ADD_REGION), add); - } - else - { - auto set = [&]() - { - auto target = child_id_get(*spritesheet, ElementType::REGION, editedReference); - if (!target) return; - auto changed = editedRegion; - changed.type = ElementType::REGION; - changed.tag = "Region"; - changed.id = editedReference; - *target = changed; - selection = {editedReference}; - }; - - window_edit(window, document, localize.get(EDIT_SET_REGION_PROPERTIES), set); - } - - frame.reference = -1; - frame.selection.clear(); - }}); - - window.popup.close(); - } - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) window.popup.close(); - - ImGui::EndPopup(); - } - - 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; - } - - Window spritesheets_window_register() - { - Window window{}; - window.title = LABEL_SPRITESHEETS_WINDOW; - window.isOpen = &Settings::windowIsSpritesheets; - window.changeType = Document::SPRITESHEETS; - window.containerType = ElementType::SPRITESHEETS; - window.elementType = ElementType::SPRITESHEET; - window.childLabel = "##Spritesheets Child"; - window.footerRows = 2; - window.flags = 0; - window.isChildPaddingZero = true; - window.popup = PopupHelper(LABEL_SPRITESHEETS_MERGE_POPUP, POPUP_SMALL_NO_HEIGHT); - window.popup2 = PopupHelper(LABEL_SPRITESHEETS_PACK_POPUP, POPUP_SMALL_NO_HEIGHT); - window.popup3 = PopupHelper(LABEL_TASKBAR_OVERWRITE_FILE, POPUP_SMALL_NO_HEIGHT); - window.storage_get = [](Document& document) -> Storage& { return document.spritesheet; }; - window.add = [](Window& window, Manager&, Settings&, Document&, Clipboard&) - { - if (window.dialog) window.dialog->file_open(Dialog::SPRITESHEET_OPEN, true); - }; - window.replace = [](Window& window, Manager&, Settings&, Document&, Clipboard&) - { - if (window.dialog) window.dialog->file_open(Dialog::SPRITESHEET_REPLACE); - }; - window.path_set = [](Window& window, Manager&, Settings&, Document&, Clipboard&) - { - if (window.dialog) window.dialog->file_save(Dialog::SPRITESHEET_PATH_SET); - }; - window.open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& selection = document.spritesheet.selection; - if (selection.size() != 1 || !window.dialog) return; - if (auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, *selection.begin())) - window_directory_open(*window.dialog, document, spritesheet->path); - }; - window.remove = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& anm2 = document.anm2; - auto unused = anm2.element_unused(ElementType::SPRITESHEET); - if (unused.empty()) return; - - auto behavior = [&]() - { - auto items = anm2.element_get(ElementType::SPRITESHEETS); - if (!items) return; - for (auto& id : unused) - { - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); - if (!spritesheet) continue; - auto pathString = path::to_utf8(spritesheet->path); - toast_log(Level::INFO, TOAST_REMOVE_SPRITESHEET, id, pathString); - element_child_id_erase(*items, ElementType::SPRITESHEET, id); - } - }; - - window_edit(window, document, localize.get(EDIT_REMOVE_UNUSED_SPRITESHEETS), behavior); - }; - window.reload = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto selected = document.spritesheet.selection; - window_edit(window, document, localize.get(EDIT_RELOAD_SPRITESHEETS), - [&]() - { - for (auto& id : selected) - document.texture_reload(id); - }); - - for (auto& id : selected) - { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); - if (!spritesheet) continue; - document.spritesheet_hash_set_saved(id); - auto pathString = path::to_utf8(spritesheet->path); - toast_log(Level::INFO, TOAST_RELOAD_SPRITESHEET, id, pathString); - } - }; - window.save = [](Window&, Manager&, Settings&, Document& document, Clipboard&) - { window_spritesheets_save(document, document.spritesheet.selection); }; - window.merge_open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& selection = document.spritesheet.selection; - if (selection.size() <= 1) return; - window.selection = selection; - window.popup.open(); - }; - window.merge = [](Window& window, Manager&, Settings& settings, Document& document, Clipboard&) - { - auto ids = window.selection.empty() ? document.spritesheet.selection : window.selection; - window_spritesheets_merge(document, ids, - {.isAppendRight = settings.mergeSpritesheetsOrigin == MERGE_APPEND_RIGHT, - .isMakeRegions = settings.mergeSpritesheetsIsMakeRegions, - .isMakePrimaryRegion = settings.mergeSpritesheetsIsMakePrimaryRegion, - .regionOrigin = (origin::Type)settings.mergeSpritesheetsRegionOrigin}); - window.selection.clear(); - }; - window.pack = [](Window& window, Manager&, Settings& settings, Document& document, Clipboard&) - { - auto id = window.editId != -1 ? window.editId - : document.spritesheet.selection.size() == 1 ? *document.spritesheet.selection.begin() - : -1; - window_spritesheet_pack(document, id, settings.packPadding); - window.editId = -1; - }; - window.copy = [](Window&, Manager&, Settings&, Document& document, Clipboard& clipboard) - { - auto& selection = document.spritesheet.selection; - if (selection.empty()) return; - - std::string clipboardText{}; - for (auto& id : selection) - if (auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id)) - clipboardText += element_to_string(*spritesheet); - clipboard.set(clipboardText); - }; - window.paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) - { - if (clipboard.is_empty()) return; - - auto& anm2 = document.anm2; - auto& selection = document.spritesheet.selection; - auto& reference = document.spritesheet.reference; - auto& region = document.region; - auto items = anm2.element_get(ElementType::SPRITESHEETS); - auto maxSpritesheetIdBefore = items ? element_child_max_id_get(*items, ElementType::SPRITESHEET) : -1; - auto pasted = anm2; - std::string errorString{}; - if (pasted.deserialize(ElementType::SPRITESHEET, clipboard.get(), true, &errorString, document.directory_get())) - { - document.snapshots.anm2_push(localize.get(EDIT_PASTE_SPRITESHEETS)); - anm2 = std::move(pasted); - if (auto pastedItems = anm2.element_get(ElementType::SPRITESHEETS)) - { - auto maxSpritesheetIdAfter = element_child_max_id_get(*pastedItems, ElementType::SPRITESHEET); - if (maxSpritesheetIdAfter > maxSpritesheetIdBefore) - { - window.newElementId = maxSpritesheetIdAfter; - selection = {maxSpritesheetIdAfter}; - reference = maxSpritesheetIdAfter; - region.reference = -1; - region.selection.clear(); - } - } - document.change(Document::SPRITESHEETS); - } - else - { - toast_log(Level::ERROR, TOAST_DESERIALIZE_SPRITESHEETS_FAILED, errorString); - } - }; - window.rows_update = - [](Window& window, Manager& manager, Settings&, Resources& resources, Clipboard&, Document& document, ImVec2) - { - auto& selection = document.spritesheet.selection; - auto& reference = document.spritesheet.reference; - auto& region = document.region; - auto style = ImGui::GetStyle(); - auto spritesheetChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 4); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); - - auto items = document.anm2.element_get(ElementType::SPRITESHEETS); - int spritesheetCount{}; - std::vector ids{}; - if (items) - for (auto& spritesheet : items->children) - if (spritesheet.type == ElementType::SPRITESHEET) - { - ++spritesheetCount; - ids.push_back(spritesheet.id); - } - - selection.start(spritesheetCount); - if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) - { - selection.clear(); - for (auto& id : ids) - selection.insert(id); - } - if (ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) - { - selection.clear(); - reference = -1; - region.reference = -1; - region.selection.clear(); - } - - int scrollTargetId = -1; - int arrowSelectionId = -1; - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && - (ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) - { - auto nextId = window_arrow_selection_get(ids, reference, selection); - if (nextId != -1) - { - arrowSelectionId = nextId; - scrollTargetId = nextId; - } - } - - if (items) - { - for (auto& spritesheet : items->children) - { - if (spritesheet.type != ElementType::SPRITESHEET) continue; - auto id = spritesheet.id; - auto isNewSpritesheet = window.newElementId == id; - ImGui::PushID(id); - - window_scroll_to_item(spritesheetChildSize.y, scrollTargetId == id); - if (scrollTargetId == id) ImGui::SetNextWindowFocus(); - - if (ImGui::BeginChild("##Spritesheet Child", spritesheetChildSize, ImGuiChildFlags_Borders)) - { - auto isSelected = selection.contains(id) || arrowSelectionId == id; - auto isReferenced = id == reference || arrowSelectionId == id; - auto cursorPos = ImGui::GetCursorPos(); - auto textureInfo = document.texture_get(id); - bool isValid = textureInfo && textureInfo->is_valid(); - auto& texture = isValid ? *textureInfo : resources.icons[icon::NONE]; - auto tintColor = !isValid ? ImVec4(1.0f, 0.25f, 0.25f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - auto pathString = path::to_utf8(spritesheet.path); - auto pathCStr = pathString.c_str(); - - ImGui::SetNextItemSelectionUserData(id); - ImGui::SetNextItemStorageID(id); - if (scrollTargetId == id) ImGui::SetKeyboardFocusHere(); - auto isActivated = ImGui::Selectable("##Spritesheet Selectable", isSelected, 0, spritesheetChildSize); - auto isClicked = - ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); - if (isActivated || isClicked) - { - document.editTarget = Document::EditTarget::SPRITESHEET; - reference = id; - region.reference = -1; - region.selection.clear(); - } - if (scrollTargetId == id) ImGui::SetItemDefaultFocus(); - if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && window.dialog) - window_directory_open(*window.dialog, document, spritesheet.path); - - auto viewport = ImGui::GetMainViewport(); - auto maxPreviewSize = to_vec2(viewport->Size) * 0.5f; - vec2 textureSize = vec2(glm::max(texture.size.x, 1), glm::max(texture.size.y, 1)); - if (textureSize.x > maxPreviewSize.x || textureSize.y > maxPreviewSize.y) - { - auto scale = glm::min(maxPreviewSize.x / textureSize.x, maxPreviewSize.y / textureSize.y); - textureSize *= scale; - } - - auto textWidth = ImGui::CalcTextSize(pathCStr).x; - auto tooltipPadding = window.tooltipWindowPadding.x * 4.0f; - auto minWidth = textureSize.x + window.tooltipItemSpacing.x + textWidth + tooltipPadding; - - ImGui::SetNextWindowSize(ImVec2(minWidth, 0), ImGuiCond_Appearing); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); - if (ImGui::BeginItemTooltip()) - { - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - auto childFlags = ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY; - auto noScrollFlags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; - if (ImGui::BeginChild("##Spritesheet Tooltip Image Child", to_imvec2(textureSize), childFlags, - noScrollFlags)) - ImGui::ImageWithBg(texture.id, to_imvec2(textureSize), ImVec2(), ImVec2(1, 1), ImVec4(), tintColor); - ImGui::EndChild(); - ImGui::PopStyleVar(); - - ImGui::SameLine(); - - auto infoChildFlags = ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY; - if (ImGui::BeginChild("##Spritesheet Info Tooltip Child", ImVec2(), infoChildFlags, noScrollFlags)) - { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(pathCStr); - ImGui::PopFont(); - - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); - - if (!isValid) - ImGui::TextUnformatted(localize.get(TOOLTIP_SPRITESHEET_INVALID)); - else - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_TEXTURE_SIZE), - std::make_format_args(texture.size.x, texture.size.y)) - .c_str()); - - ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); - } - ImGui::EndChild(); - - ImGui::EndTooltip(); - } - ImGui::PopStyleVar(2); - - auto imageSize = to_imvec2(vec2(spritesheetChildSize.y)); - auto aspectRatio = texture.size.y != 0 ? (float)texture.size.x / texture.size.y : 1.0f; - - if (imageSize.x / imageSize.y > aspectRatio) - imageSize.x = imageSize.y * aspectRatio; - else - imageSize.y = imageSize.x / aspectRatio; - - ImGui::SetCursorPos(cursorPos); - ImGui::ImageWithBg(texture.id, imageSize, ImVec2(), ImVec2(1, 1), ImVec4(), tintColor); - - ImGui::SetCursorPos( - ImVec2(spritesheetChildSize.y + style.ItemSpacing.x, - spritesheetChildSize.y - spritesheetChildSize.y / 2 - ImGui::GetTextLineHeight() / 2)); - - if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); - auto spritesheetLabel = std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(id, pathCStr)); - if (document.spritesheet_is_dirty(id)) - spritesheetLabel = - std::vformat(localize.get(FORMAT_SPRITESHEET_NOT_SAVED), std::make_format_args(spritesheetLabel)); - ImGui::TextUnformatted(spritesheetLabel.c_str()); - if (isReferenced) ImGui::PopFont(); - } - - ImGui::EndChild(); - - if (isNewSpritesheet && !is_drag_drop_active()) - { - ImGui::SetScrollHereY(0.5f); - window.newElementId = -1; - } - - ImGui::PopID(); - } - } - - ImGui::PopStyleVar(); - selection.finish(); - if (arrowSelectionId != -1) - { - document.editTarget = Document::EditTarget::SPRITESHEET; - selection = {arrowSelectionId}; - reference = arrowSelectionId; - region.reference = -1; - region.selection.clear(); - } - if (shortcut(manager.chords[SHORTCUT_CONFIRM], shortcut::FOCUSED) && reference != -1 && window.dialog) - if (auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, reference)) - window_directory_open(*window.dialog, document, spritesheet->path); - }; - window.context_update = - [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard& clipboard, Document& document) - { - auto& selection = document.spritesheet.selection; - auto style = ImGui::GetStyle(); - auto is_regions_empty = [&](int id) - { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); - if (!spritesheet) return true; - for (auto& child : spritesheet->children) - if (child.type == ElementType::REGION) return false; - return true; - }; - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && - ImGui::IsMouseClicked(ImGuiMouseButton_Right)) - ImGui::OpenPopup("##Spritesheet Context Menu"); - - auto isPackable = selection.size() == 1 && - document.anm2.element_get(ElementType::SPRITESHEET, *selection.begin()) && - !is_regions_empty(*selection.begin()); - Actions actions{}; - actions_undo_redo_add(actions, manager, document); - actions.separator(); - actions.add( - ACTION_OPEN_DIRECTORY, [&]() { return selection.size() == 1 && (bool)window.open; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.open); }); - actions.add( - ACTION_SET_FILE_PATH, [&]() { return selection.size() == 1 && (bool)window.path_set; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.path_set); }); - actions.add( - ACTION_ADD, [&]() { return (bool)window.add; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }); - actions.add( - ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); - actions.add( - ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }); - actions.add( - ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }); - actions.add( - ACTION_MERGE, [&]() { return selection.size() > 1 && (bool)window.merge_open; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.merge_open); }); - actions.add( - ACTION_PACK, [&]() { return isPackable; }, - [&]() - { - window.editId = *selection.begin(); - window.popup2.open(); - }, - TOOLTIP_PACK_SPRITESHEET); - actions.add( - ACTION_SAVE, [&]() { return !selection.empty(); }, - [&]() - { - if (settings.fileIsWarnOverwrite) - { - window.selection2 = selection; - window.popup3.open(); - } - else if (window.save) - window_command_run(window, manager, settings, document, clipboard, window.save); - }, - TOOLTIP_SAVE_SPRITESHEETS); - actions.separator(); - actions.add( - ACTION_COPY, [&]() { return !selection.empty() && (bool)window.copy; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.copy); }); - actions.add( - ACTION_PASTE, [&]() { return !clipboard.is_empty() && (bool)window.paste; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.paste); }); - actions_popup_draw("##Spritesheet Context Menu", actions, settings); - ImGui::PopStyleVar(2); - }; - window.footer_update = - [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard& clipboard, Document& document) - { - auto& selection = document.spritesheet.selection; - - auto rowOneWidgetSize = widget_size_with_row_get(3); - Actions rowOneActions{}; - rowOneActions.add( - ACTION_ADD, [&]() { return (bool)window.add; }, [&]() - { window_command_run(window, manager, settings, document, clipboard, window.add); }, TOOLTIP_ADD_SPRITESHEET); - rowOneActions.add( - ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }, - TOOLTIP_RELOAD_SPRITESHEETS); - rowOneActions.add( - ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }, - TOOLTIP_REPLACE_SPRITESHEET); - - bool isSameLine{}; - for (auto& action : rowOneActions.items) - action_button_draw(action, manager, settings, rowOneWidgetSize, isSameLine); - - if (window.dialog && window.dialog->is_selected(Dialog::SPRITESHEET_OPEN)) - { - auto paths = window.dialog->paths; - manager.command_push({manager.selected, [&window, paths](Manager&, Document& document) - { - document.spritesheets_add(paths); - document.region.reference = -1; - document.region.selection.clear(); - window.newElementId = document.spritesheet.reference; - }}); - window.dialog->reset(); - } - - if (window.dialog && window.dialog->is_selected(Dialog::SPRITESHEET_REPLACE)) - { - if (selection.size() == 1 && !window.dialog->path.empty()) - { - auto id = *selection.begin(); - auto dialogPath = window.dialog->path; - manager.command_push({manager.selected, [id, dialogPath](Manager&, Document& document) - { - auto behavior = [&]() - { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); - if (!spritesheet) return; - spritesheet->path = window_asset_path_get(document, dialogPath); - document.texture_reload(id); - }; - - window_edit(document, Document::SPRITESHEETS, localize.get(EDIT_REPLACE_SPRITESHEET), - behavior); - if (auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id)) - { - document.spritesheet_hash_set_saved(id); - auto pathString = path::to_utf8(spritesheet->path); - toast_log(Level::INFO, TOAST_REPLACE_SPRITESHEET, id, pathString); - } - }}); - } - window.dialog->reset(); - } - - if (window.dialog && window.dialog->is_selected(Dialog::SPRITESHEET_PATH_SET)) - { - if (selection.size() == 1 && !window.dialog->path.empty()) - { - auto id = *selection.begin(); - auto dialogPath = window.dialog->path; - manager.command_push({manager.selected, [id, dialogPath](Manager&, Document& document) - { - auto behavior = [&]() - { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); - auto texture = document.texture_get(id); - if (!spritesheet || !texture) return; - auto newPath = window_asset_path_get(document, dialogPath); - auto pathString = path::to_utf8(newPath); - WorkingDirectory workingDirectory(document.directory_get()); - path::ensure_directory(newPath.parent_path()); - if (!texture->write_png(newPath)) - { - toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); - return; - } - spritesheet->path = newPath; - document.texturePaths[id] = spritesheet->path; - document.spritesheet_hash_set_saved(id); - toast_log(Level::INFO, TOAST_SAVE_SPRITESHEET, id, pathString); - }; - - window_edit(document, Document::SPRITESHEETS, - localize.get(EDIT_SET_SPRITESHEET_FILE_PATH), behavior); - }}); - } - window.dialog->reset(); - } - - auto rowTwoWidgetSize = widget_size_with_row_get(2); - Actions rowTwoActions{}; - rowTwoActions.add( - ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }, - TOOLTIP_REMOVE_UNUSED_SPRITESHEETS); - rowTwoActions.add( - ACTION_SAVE, [&]() { return !selection.empty(); }, - [&]() - { - if (settings.fileIsWarnOverwrite) - { - window.selection2 = selection; - window.popup3.open(); - } - else if (window.save) - window_command_run(window, manager, settings, document, clipboard, window.save); - }, - TOOLTIP_SAVE_SPRITESHEETS); - - isSameLine = false; - for (auto& action : rowTwoActions.items) - action_button_draw(action, manager, settings, rowTwoWidgetSize, isSameLine); - - if (shortcut(manager.chords[SHORTCUT_ADD], shortcut::FOCUSED) && window.add) - window_command_run(window, manager, settings, document, clipboard, window.add); - if (shortcut(manager.chords[SHORTCUT_REMOVE], shortcut::FOCUSED) && window.remove) - window_command_run(window, manager, settings, document, clipboard, window.remove); - if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED) && window.copy) - window_command_run(window, manager, settings, document, clipboard, window.copy); - if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED) && window.paste) - window_command_run(window, manager, settings, document, clipboard, window.paste); - if (shortcut(manager.chords[SHORTCUT_MERGE], shortcut::FOCUSED) && selection.size() > 1 && window.merge_open) - window_command_run(window, manager, settings, document, clipboard, window.merge_open); - }; - window.popup_update = - [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard&, Document& document) - { - window.popup.trigger(); - if (ImGui::BeginPopupModal(window.popup.label(), &window.popup.isOpen, ImGuiWindowFlags_NoResize)) - { - settings.mergeSpritesheetsRegionOrigin = - glm::clamp(settings.mergeSpritesheetsRegionOrigin, (int)origin::TOP_LEFT, (int)origin::ORIGIN_CENTER); - - auto close = [&]() - { - window.selection.clear(); - window.popup.close(); - }; - - auto optionsSize = child_size_get(6); - if (ImGui::BeginChild("##Merge Spritesheets Options", optionsSize, ImGuiChildFlags_Borders)) - { - ImGui::SeparatorText(localize.get(LABEL_REGION_PROPERTIES_ORIGIN)); - ImGui::RadioButton(localize.get(LABEL_MERGE_SPRITESHEETS_APPEND_BOTTOM), &settings.mergeSpritesheetsOrigin, - MERGE_APPEND_BOTTOM); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_SPRITESHEETS_BOTTOM_LEFT)); - ImGui::SameLine(); - ImGui::RadioButton(localize.get(LABEL_MERGE_SPRITESHEETS_APPEND_RIGHT), &settings.mergeSpritesheetsOrigin, - MERGE_APPEND_RIGHT); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_SPRITESHEETS_TOP_RIGHT)); - - ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); - ImGui::Checkbox(localize.get(LABEL_MERGE_MAKE_SPRITESHEET_REGIONS), &settings.mergeSpritesheetsIsMakeRegions); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_MAKE_SPRITESHEET_REGIONS)); - - ImGui::BeginDisabled(!settings.mergeSpritesheetsIsMakeRegions); - ImGui::Checkbox(localize.get(LABEL_MERGE_MAKE_PRIMARY_SPRITESHEET_REGION), - &settings.mergeSpritesheetsIsMakePrimaryRegion); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_MERGE_MAKE_PRIMARY_SPRITESHEET_REGION)); - - const char* regionOriginOptions[] = {localize.get(LABEL_REGION_ORIGIN_TOP_LEFT), - localize.get(LABEL_REGION_ORIGIN_CENTER)}; - ImGui::Combo(localize.get(LABEL_REGION_PROPERTIES_ORIGIN), &settings.mergeSpritesheetsRegionOrigin, - regionOriginOptions, IM_ARRAYSIZE(regionOriginOptions)); - ImGui::EndDisabled(); - } - ImGui::EndChild(); - - auto widgetSize = widget_size_with_row_get(2); - shortcut(manager.chords[SHORTCUT_CONFIRM]); - ImGui::BeginDisabled(window.selection.size() <= 1); - if (ImGui::Button(localize.get(BASIC_MERGE), widgetSize)) - { - auto queuedSelection = window.selection; - SpritesheetMergeOptions options{.isAppendRight = settings.mergeSpritesheetsOrigin == MERGE_APPEND_RIGHT, - .isMakeRegions = settings.mergeSpritesheetsIsMakeRegions, - .isMakePrimaryRegion = settings.mergeSpritesheetsIsMakePrimaryRegion, - .regionOrigin = (origin::Type)settings.mergeSpritesheetsRegionOrigin}; - manager.command_push({manager.selected, [queuedSelection, options](Manager&, Document& document) mutable - { window_spritesheets_merge(document, queuedSelection, options); }}); - close(); - } - ImGui::EndDisabled(); - - ImGui::SameLine(); - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) close(); - - ImGui::EndPopup(); - } - window.popup.end(); - - window.popup2.trigger(); - if (ImGui::BeginPopupModal(window.popup2.label(), &window.popup2.isOpen, ImGuiWindowFlags_NoResize)) - { - settings.packPadding = std::max(0, settings.packPadding); - - auto close = [&]() - { - window.editId = -1; - window.popup2.close(); - }; - - auto optionsSize = child_size_get(1); - if (ImGui::BeginChild("##Pack Spritesheet Options", optionsSize, ImGuiChildFlags_Borders)) - ImGui::DragInt(localize.get(LABEL_PACK_PADDING), &settings.packPadding, DRAG_SPEED, 0, PADDING_MAX); - ImGui::EndChild(); - - auto widgetSize = widget_size_with_row_get(2); - shortcut(manager.chords[SHORTCUT_CONFIRM]); - auto spritesheet = - window.editId != -1 ? document.anm2.element_get(ElementType::SPRITESHEET, window.editId) : nullptr; - bool isPackable{}; - if (spritesheet) - for (auto& child : spritesheet->children) - if (child.type == ElementType::REGION) isPackable = true; - ImGui::BeginDisabled(!isPackable); - if (ImGui::Button(localize.get(BASIC_PACK), widgetSize)) - { - auto queuedEditId = window.editId; - auto queuedPadding = settings.packPadding; - manager.command_push({manager.selected, [queuedEditId, queuedPadding](Manager&, Document& document) mutable - { window_spritesheet_pack(document, queuedEditId, queuedPadding); }}); - close(); - } - ImGui::EndDisabled(); - - ImGui::SameLine(); - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) close(); - - ImGui::EndPopup(); - } - window.popup2.end(); - - window.popup3.trigger(); - if (ImGui::BeginPopupModal(window.popup3.label(), &window.popup3.isOpen, ImGuiWindowFlags_NoResize)) - { - ImGui::TextUnformatted(localize.get(LABEL_OVERWRITE_CONFIRMATION)); - - auto widgetSize = widget_size_with_row_get(2); - - if (ImGui::Button(localize.get(BASIC_YES), widgetSize)) - { - auto queuedSelection = window.selection2; - manager.command_push({manager.selected, [queuedSelection](Manager&, Document& document) mutable - { window_spritesheets_save(document, queuedSelection); }}); - window.selection2.clear(); - window.popup3.close(); - } - - ImGui::SameLine(); - - if (ImGui::Button(localize.get(BASIC_NO), widgetSize)) - { - window.selection2.clear(); - window.popup3.close(); - } - - ImGui::EndPopup(); - } - window.popup3.end(); - }; - return window; - } - - Window sounds_window_register() - { - Window window{}; - window.title = LABEL_SOUNDS_WINDOW; - window.isOpen = &Settings::windowIsSounds; - window.changeType = Document::SOUNDS; - window.containerType = ElementType::SOUNDS; - window.elementType = ElementType::SOUND_ELEMENT; - window.childLabel = "##Sounds Child"; - window.footerRows = 1; - window.flags = 0; - window.isChildPaddingZero = true; - window.storage_get = [](Document& document) -> Storage& { return document.sound; }; - window.add = [](Window& window, Manager&, Settings&, Document&, Clipboard&) - { - if (window.dialog) window.dialog->file_open(Dialog::SOUND_OPEN, true); - }; - window.remove = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto unused = document.anm2.element_unused(ElementType::SOUND_ELEMENT); - if (unused.empty()) return; - - auto behavior = [&]() - { - auto sounds = document.anm2.element_get(ElementType::SOUNDS); - if (!sounds) return; - for (auto& id : unused) - element_child_id_erase(*sounds, ElementType::SOUND_ELEMENT, id); - }; - - window_edit(window, document, localize.get(EDIT_REMOVE_UNUSED_SOUNDS), behavior); - }; - window.reload = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& selection = document.sound.selection; - auto behavior = [&]() - { - for (auto& id : selection) - { - auto sound = window_element_get(window, document.anm2, id); - if (!sound) continue; - document.sound_reload(id); - auto pathString = path::to_utf8(sound->path); - toast_log(Level::INFO, TOAST_RELOAD_SOUND, id, pathString); - } - }; - - window_edit(window, document, localize.get(EDIT_RELOAD_SOUNDS), behavior); - }; - window.replace = [](Window& window, Manager&, Settings&, Document&, Clipboard&) - { - if (window.dialog) window.dialog->file_open(Dialog::SOUND_REPLACE); - }; - window.open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& selection = document.sound.selection; - if (selection.size() != 1 || !window.dialog) return; - if (auto sound = window_element_get(window, document.anm2, *selection.begin())) - window_directory_open(*window.dialog, document, sound->path); - }; - window.copy = [](Window&, Manager&, Settings&, Document& document, Clipboard& clipboard) - { - auto& selection = document.sound.selection; - if (selection.empty()) return; - - std::string clipboardText{}; - auto sounds = document.anm2.element_get(ElementType::SOUNDS); - if (!sounds) return; - for (auto& id : selection) - if (auto sound = child_id_get(*sounds, ElementType::SOUND_ELEMENT, id)) - clipboardText += element_to_string(*sound); - clipboard.set(clipboardText); - }; - window.paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) - { - if (clipboard.is_empty()) return; - - auto& anm2 = document.anm2; - auto& reference = document.sound.reference; - auto& selection = document.sound.selection; - auto sounds = anm2.element_get(ElementType::SOUNDS); - auto maxSoundIdBefore = sounds ? element_child_max_id_get(*sounds, ElementType::SOUND_ELEMENT) : -1; - auto pasted = anm2; - std::string errorString{}; - if (pasted.deserialize(ElementType::SOUND_ELEMENT, clipboard.get(), true, &errorString, document.directory_get())) - { - document.snapshots.anm2_push(localize.get(TOAST_SOUNDS_PASTE)); - anm2 = std::move(pasted); - if (auto pastedSounds = anm2.element_get(ElementType::SOUNDS)) - { - auto maxSoundIdAfter = element_child_max_id_get(*pastedSounds, ElementType::SOUND_ELEMENT); - if (maxSoundIdAfter > maxSoundIdBefore) - { - window.newElementId = maxSoundIdAfter; - selection = {maxSoundIdAfter}; - reference = maxSoundIdAfter; - } - } - document.change(Document::SOUNDS); - } - else - { - toast_log(Level::ERROR, TOAST_SOUNDS_DESERIALIZE_ERROR, errorString); - } - }; - window.rows_update = [](Window& window, Manager& manager, Settings& settings, Resources& resources, - Clipboard& clipboard, Document& document, ImVec2) - { - auto& reference = document.sound.reference; - auto& selection = document.sound.selection; - auto style = ImGui::GetStyle(); - auto soundChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 2); - auto sounds = document.anm2.element_get(ElementType::SOUNDS); - int soundCount{}; - std::vector ids{}; - if (sounds) - for (auto& sound : sounds->children) - if (sound.type == ElementType::SOUND_ELEMENT) - { - ++soundCount; - ids.push_back(sound.id); - } - - auto play = [&](int id) - { - if (auto audio = document.sound_get(id)) audio->play(); - }; - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); - selection.start(soundCount); - if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) - { - selection.clear(); - for (auto& id : ids) - selection.insert(id); - } - if (ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) selection.clear(); - - int scrollTargetId = -1; - int arrowSelectionId = -1; - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && - (ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) - { - auto nextId = window_arrow_selection_get(ids, reference, selection); - if (nextId != -1) - { - arrowSelectionId = nextId; - scrollTargetId = nextId; - } - } - - if (sounds) - { - for (auto& sound : sounds->children) - { - if (sound.type != ElementType::SOUND_ELEMENT) continue; - auto id = sound.id; - auto isNewSound = window.newElementId == id; - ImGui::PushID(id); - - window_scroll_to_item(soundChildSize.y, scrollTargetId == id); - if (scrollTargetId == id) ImGui::SetNextWindowFocus(); - - if (ImGui::BeginChild("##Sound Child", soundChildSize, ImGuiChildFlags_Borders)) - { - auto isSelected = selection.contains(id) || arrowSelectionId == id; - auto cursorPos = ImGui::GetCursorPos(); - auto audio = document.sound_get(id); - bool isValid = audio && audio->is_valid(); - auto& soundIcon = isValid ? resources.icons[icon::SOUND] : resources.icons[icon::NONE]; - auto tintColor = !isValid ? ImVec4(1.0f, 0.25f, 0.25f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - auto pathString = path::to_utf8(sound.path); - - ImGui::SetNextItemSelectionUserData(id); - ImGui::SetNextItemStorageID(id); - if (scrollTargetId == id) ImGui::SetKeyboardFocusHere(); - auto isActivated = ImGui::Selectable("##Sound Selectable", isSelected, 0, soundChildSize); - auto isClicked = - ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); - if (isActivated || isClicked) - { - reference = id; - if (ImGui::IsItemClicked(ImGuiMouseButton_Left)) play(id); - } - if (scrollTargetId == id) ImGui::SetItemDefaultFocus(); - if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && window.dialog) - window_directory_open(*window.dialog, document, sound.path); - - auto textWidth = ImGui::CalcTextSize(pathString.c_str()).x; - auto tooltipPadding = window.tooltipWindowPadding.x * 4.0f; - auto minWidth = textWidth + window.tooltipItemSpacing.x + tooltipPadding; - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); - ImGui::SetNextWindowSize(ImVec2(minWidth, 0), ImGuiCond_Appearing); - if (ImGui::BeginItemTooltip()) - { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(pathString.c_str()); - ImGui::PopFont(); - ImGui::Text("%s: %d", localize.get(BASIC_ID), id); - if (!isValid) - { - ImGui::Spacing(); - ImGui::TextWrapped("%s", localize.get(TOOLTIP_SOUND_INVALID)); - } - else - { - ImGui::Text("%s", localize.get(TEXT_OPEN_DIRECTORY)); - } - ImGui::EndTooltip(); - } - ImGui::PopStyleVar(2); - - ImGui::SetCursorPos(cursorPos); - auto imageSize = to_imvec2(vec2(soundChildSize.y)); - ImGui::ImageWithBg(soundIcon.id, imageSize, ImVec2(), ImVec2(1, 1), ImVec4(), tintColor); - - ImGui::SetCursorPos(ImVec2(soundChildSize.y + style.ItemSpacing.x, - soundChildSize.y - soundChildSize.y / 2 - ImGui::GetTextLineHeight() / 2)); - - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)).c_str()); - } - - ImGui::EndChild(); - - if (isNewSound && !is_drag_drop_active()) - { - ImGui::SetScrollHereY(0.5f); - window.newElementId = -1; - } - - ImGui::PopID(); - } - } - - ImGui::PopStyleVar(); - selection.finish(); - if (arrowSelectionId != -1) - { - selection = {arrowSelectionId}; - reference = arrowSelectionId; - } - if (shortcut(manager.chords[SHORTCUT_CONFIRM], shortcut::FOCUSED) && reference != -1 && window.dialog) - if (auto sound = document.anm2.element_get(ElementType::SOUND_ELEMENT, reference)) - window_directory_open(*window.dialog, document, sound->path); - - if (shortcut(manager.chords[SHORTCUT_ADD], shortcut::FOCUSED) && window.add) - window_command_run(window, manager, settings, document, clipboard, window.add); - if (shortcut(manager.chords[SHORTCUT_REMOVE], shortcut::FOCUSED) && window.remove) - window_command_run(window, manager, settings, document, clipboard, window.remove); - if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED) && window.copy) - window_command_run(window, manager, settings, document, clipboard, window.copy); - if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED) && window.paste) - window_command_run(window, manager, settings, document, clipboard, window.paste); - }; - window.context_update = - [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard& clipboard, Document& document) - { - auto& selection = document.sound.selection; - auto style = ImGui::GetStyle(); - auto play = [&](int id) - { - if (auto audio = document.sound_get(id)) audio->play(); - }; - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && - ImGui::IsMouseClicked(ImGuiMouseButton_Right)) - ImGui::OpenPopup("##Sound Context Menu"); - - Actions actions{}; - actions_undo_redo_add(actions, manager, document); - actions.separator(); - actions.add( - ACTION_PLAY, [&]() { return selection.size() == 1; }, [&]() { play(*selection.begin()); }, STRING_UNDEFINED, - -1); - actions.add( - ACTION_OPEN_DIRECTORY, [&]() { return selection.size() == 1 && (bool)window.open; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.open); }); - actions.add( - ACTION_ADD, [&]() { return (bool)window.add; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }); - actions.add( - ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); - actions.add( - ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }); - actions.add( - ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }); - actions.separator(); - actions.add( - ACTION_COPY, [&]() { return !selection.empty() && (bool)window.copy; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.copy); }); - actions.add( - ACTION_PASTE, [&]() { return !clipboard.is_empty() && (bool)window.paste; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.paste); }); - actions_popup_draw("##Sound Context Menu", actions, settings); - ImGui::PopStyleVar(2); - }; - window.footer_update = - [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard& clipboard, Document& document) - { - auto& selection = document.sound.selection; - auto widgetSize = widget_size_with_row_get(4); - - shortcut(manager.chords[SHORTCUT_ADD]); - if (ImGui::Button(localize.get(BASIC_ADD), widgetSize) && window.add) - window_command_run(window, manager, settings, document, clipboard, window.add); - set_item_tooltip_shortcut(localize.get(TOOLTIP_SOUND_ADD), settings.shortcutAdd); - - if (window.dialog && window.dialog->is_selected(Dialog::SOUND_OPEN)) - { - auto paths = window.dialog->paths; - manager.command_push({manager.selected, [&window, paths](Manager&, Document& document) - { - document.sounds_add(paths); - window.newElementId = document.sound.reference; - }}); - window.dialog->reset(); - } - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_REMOVE]); - if (ImGui::Button(localize.get(BASIC_REMOVE_UNUSED), widgetSize) && window.remove) - window_command_run(window, manager, settings, document, clipboard, window.remove); - set_item_tooltip_shortcut(localize.get(TOOLTIP_REMOVE_UNUSED_SOUNDS), settings.shortcutRemove); - - ImGui::SameLine(); - - ImGui::BeginDisabled(selection.empty()); - if (ImGui::Button(localize.get(BASIC_RELOAD), widgetSize) && window.reload) - window_command_run(window, manager, settings, document, clipboard, window.reload); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RELOAD_SOUNDS)); - ImGui::EndDisabled(); - - ImGui::SameLine(); - - ImGui::BeginDisabled(selection.size() != 1); - if (ImGui::Button(localize.get(BASIC_REPLACE), widgetSize) && window.replace) - window_command_run(window, manager, settings, document, clipboard, window.replace); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REPLACE_SOUND)); - ImGui::EndDisabled(); - - if (window.dialog && window.dialog->is_selected(Dialog::SOUND_REPLACE)) - { - if (selection.size() == 1 && !window.dialog->path.empty()) - { - auto id = *selection.begin(); - auto dialogPath = window.dialog->path; - manager.command_push({manager.selected, [id, dialogPath](Manager&, Document& document) - { - auto behavior = [&]() - { - auto sound = document.anm2.element_get(ElementType::SOUND_ELEMENT, id); - if (!sound) return; - sound->path = window_asset_path_get(document, dialogPath); - document.sound_reload(id); - auto pathString = path::to_utf8(sound->path); - toast_log(Level::INFO, TOAST_REPLACE_SOUND, id, pathString); - }; - - window_edit(document, Document::SOUNDS, localize.get(EDIT_REPLACE_SOUND), behavior); - }}); - } - window.dialog->reset(); - } - }; - return window; - } - - Window layers_window_register() - { - Window window{}; - window.title = LABEL_LAYERS_WINDOW; - window.isOpen = &Settings::windowIsLayers; - window.changeType = Document::LAYERS; - window.containerType = ElementType::LAYERS; - window.elementType = ElementType::LAYER_ELEMENT; - window.childLabel = "##Layers Child"; - window.addTooltip = TOOLTIP_ADD_LAYER; - window.removeUnusedTooltip = TOOLTIP_REMOVE_UNUSED_LAYERS; - window.pasteEdit = EDIT_PASTE_LAYERS; - window.removeUnusedEdit = EDIT_REMOVE_UNUSED_LAYERS; - window.deserializeFailedToast = TOAST_DESERIALIZE_LAYERS_FAILED; - window.flags = WINDOW_ADD | WINDOW_REMOVE_UNUSED | WINDOW_COPY | WINDOW_PASTE | WINDOW_PROPERTIES; - window.storage_get = [](Document& document) -> Storage& { return document.layer; }; - window.row_label_get = [](Document&, const Element& layer) - { - return std::vformat(localize.get(FORMAT_LAYER), std::make_format_args(layer.id, layer.name, layer.spritesheetId)); - }; - window.tooltip_draw = [](Document&, Resources& resources, const Element& layer) - { - ImGui::PushFont(resources.fonts[resource::font::BOLD].get(), resource::font::SIZE); - ImGui::TextUnformatted(layer.name.c_str()); - ImGui::PopFont(); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(layer.id)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_SPRITESHEET_ID), std::make_format_args(layer.spritesheetId)).c_str()); - }; - window.properties_open = [](Manager& manager, int id) { manager.layer_properties_open(id); }; - window.popup_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) - { - auto& reference = document.layer.reference; - auto& propertiesPopup = manager.layerPropertiesPopup; - - manager.layer_properties_trigger(); - - if (ImGui::BeginPopupModal(propertiesPopup.label(), &propertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) - { - auto childSize = child_size_get(2); - auto& layer = manager.editLayer; - - if (ImGui::BeginChild("##Child", childSize, ImGuiChildFlags_Borders)) - { - if (propertiesPopup.isJustOpened) ImGui::SetKeyboardFocusHere(); - input_text_string(localize.get(BASIC_NAME), &layer.name); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); - - combo_id_mapped(localize.get(LABEL_SPRITESHEET), &layer.spritesheetId, document.spritesheet.ids, - document.spritesheet.labels); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SPRITESHEET)); - } - ImGui::EndChild(); - - auto widgetSize = widget_size_with_row_get(2); - - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(reference == -1 ? localize.get(BASIC_ADD) : localize.get(BASIC_CONFIRM), widgetSize)) - { - auto editedLayer = layer; - auto editedReference = reference; - manager.command_push({manager.selected, [&window, editedLayer, editedReference](Manager&, Document& document) - { - auto behavior = [&]() - { - auto layers = document.anm2.element_get(ElementType::LAYERS); - if (!layers) return; - auto changed = editedLayer; - changed.type = ElementType::LAYER_ELEMENT; - changed.tag = "Layer"; - - if (editedReference == -1) - { - auto id = element_child_next_id_get(*layers, ElementType::LAYER_ELEMENT); - changed.id = id; - layers->children.push_back(changed); - document.layer.selection = {id}; - document.layer.reference = id; - window.newElementId = id; - return; - } - - auto target = child_id_get(*layers, ElementType::LAYER_ELEMENT, editedReference); - if (!target) return; - changed.id = editedReference; - *target = changed; - document.layer.selection = {editedReference}; - }; - - window_edit( - document, Document::LAYERS, - localize.get(editedReference == -1 ? EDIT_ADD_LAYER : EDIT_SET_LAYER_PROPERTIES), - behavior); - }}); - - manager.layer_properties_close(); - } - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) manager.layer_properties_close(); - - manager.layer_properties_end(); - ImGui::EndPopup(); - } - }; - return window; - } - - Window nulls_window_register() - { - Window window{}; - window.title = LABEL_NULLS_WINDOW; - window.isOpen = &Settings::windowIsNulls; - window.changeType = Document::NULLS; - window.containerType = ElementType::NULLS; - window.elementType = ElementType::NULL_ELEMENT; - window.childLabel = "##Nulls Child"; - window.addTooltip = TOOLTIP_ADD_NULL; - window.removeUnusedTooltip = TOOLTIP_REMOVE_UNUSED_NULLS; - window.pasteEdit = EDIT_PASTE_NULLS; - window.removeUnusedEdit = EDIT_REMOVE_UNUSED_NULLS; - window.deserializeFailedToast = TOAST_DESERIALIZE_NULLS_FAILED; - window.flags = - WINDOW_ADD | WINDOW_REMOVE_UNUSED | WINDOW_COPY | WINDOW_PASTE | WINDOW_PROPERTIES | WINDOW_REFERENCE_ITALIC; - window.storage_get = [](Document& document) -> Storage& { return document.null; }; - window.row_label_get = [](Document&, const Element& null) - { return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(null.id, null.name)); }; - window.tooltip_draw = [](Document&, Resources& resources, const Element& element) - { - ImGui::PushFont(resources.fonts[resource::font::BOLD].get(), resource::font::SIZE); - ImGui::TextUnformatted(element.name.c_str()); - ImGui::PopFont(); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(element.id)).c_str()); - }; - window.properties_open = [](Manager& manager, int id) { manager.null_properties_open(id); }; - window.popup_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) - { - auto& reference = document.null.reference; - auto& propertiesPopup = manager.nullPropertiesPopup; - - manager.null_properties_trigger(); - - if (ImGui::BeginPopupModal(propertiesPopup.label(), &propertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) - { - auto childSize = child_size_get(2); - auto& null = manager.editNull; - - if (ImGui::BeginChild("##Child", childSize, ImGuiChildFlags_Borders)) - { - if (propertiesPopup.isJustOpened) ImGui::SetKeyboardFocusHere(); - input_text_string(localize.get(BASIC_NAME), &null.name); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_NAME)); - - ImGui::Checkbox(localize.get(LABEL_RECT), &null.isShowRect); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_RECT)); - } - ImGui::EndChild(); - - auto widgetSize = widget_size_with_row_get(2); - - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(reference == -1 ? localize.get(BASIC_ADD) : localize.get(BASIC_CONFIRM), widgetSize)) - { - auto editedNull = null; - auto editedReference = reference; - manager.command_push( - {manager.selected, [&window, editedNull, editedReference](Manager&, Document& document) - { - auto behavior = [&]() - { - auto nulls = document.anm2.element_get(ElementType::NULLS); - if (!nulls) return; - auto changed = editedNull; - changed.type = ElementType::NULL_ELEMENT; - changed.tag = "Null"; - - if (editedReference == -1) - { - auto id = element_child_next_id_get(*nulls, ElementType::NULL_ELEMENT); - changed.id = id; - nulls->children.push_back(changed); - document.null.selection = {id}; - document.null.reference = id; - window.newElementId = id; - return; - } - - auto target = child_id_get(*nulls, ElementType::NULL_ELEMENT, editedReference); - if (!target) return; - changed.id = editedReference; - *target = changed; - document.null.selection = {editedReference}; - }; - - window_edit(document, Document::NULLS, - localize.get(editedReference == -1 ? EDIT_ADD_NULL : EDIT_SET_NULL_PROPERTIES), behavior); - }}); - - manager.null_properties_close(); - } - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) manager.null_properties_close(); - - ImGui::EndPopup(); - } - - manager.null_properties_end(); - }; - return window; - } - - Window events_window_register() - { - Window window{}; - window.title = LABEL_EVENTS_WINDOW; - window.isOpen = &Settings::windowIsEvents; - window.changeType = Document::EVENTS; - window.containerType = ElementType::EVENTS; - window.elementType = ElementType::EVENT_ELEMENT; - window.childLabel = "##Events Child"; - window.addTooltip = TOOLTIP_ADD_EVENT; - window.removeUnusedTooltip = TOOLTIP_REMOVE_UNUSED_EVENTS; - window.addEdit = EDIT_ADD_EVENT; - window.renameEdit = EDIT_RENAME_EVENT; - window.pasteEdit = EDIT_PASTE_EVENTS; - window.removeUnusedEdit = EDIT_REMOVE_UNUSED_EVENTS; - window.deserializeFailedToast = TOAST_DESERIALIZE_EVENTS_FAILED; - window.flags = WINDOW_ADD | WINDOW_REMOVE_UNUSED | WINDOW_COPY | WINDOW_PASTE | WINDOW_RENAME; - window.storage_get = [](Document& document) -> Storage& { return document.event; }; - window.tooltip_draw = [](Document&, Resources& resources, const Element& element) - { - ImGui::PushFont(resources.fonts[resource::font::BOLD].get(), resource::font::SIZE); - ImGui::TextUnformatted(element.name.c_str()); - ImGui::PopFont(); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(element.id)).c_str()); - }; - window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto behavior = [&]() - { - auto events = document.anm2.element_get(ElementType::EVENTS); - if (!events) return; - - auto id = element_child_next_id_get(*events, ElementType::EVENT_ELEMENT); - auto event = element_make(ElementType::EVENT_ELEMENT); - event.id = id; - event.name = localize.get(TEXT_NEW_EVENT); - events->children.push_back(event); - - auto& storage = window.storage_get(document); - storage.selection = {id}; - storage.reference = id; - window.newElementId = id; - }; - - window_edit(window, document, localize.get(window.addEdit), behavior); - }; - return window; - } } diff --git a/src/imgui/window/window.hpp b/src/imgui/window/window.hpp index 007052f..1999644 100644 --- a/src/imgui/window/window.hpp +++ b/src/imgui/window/window.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -16,30 +17,69 @@ namespace anm2ed::imgui { +#define WINDOW_FLAGS \ + X(PLAY, ACTION_PLAY, play) \ + X(RENAME, ACTION_RENAME, rename) \ + X(PROPERTIES, ACTION_PROPERTIES, properties) \ + X(OPEN_DIRECTORY, ACTION_OPEN_DIRECTORY, open) \ + X(SET_FILE_PATH, ACTION_SET_FILE_PATH, path_set) \ + X(ADD, ACTION_ADD, add) \ + X(DUPLICATE, ACTION_DUPLICATE, duplicate) \ + X(REMOVE_UNUSED, ACTION_REMOVE_UNUSED, remove_unused) \ + X(RELOAD, ACTION_RELOAD, reload) \ + X(REPLACE, ACTION_REPLACE, replace) \ + X(MERGE, ACTION_MERGE, merge) \ + X(GROUP, ACTION_GROUP, group) \ + X(REMOVE, ACTION_REMOVE, remove) \ + X(DEFAULT, ACTION_DEFAULT, default_set) \ + X(TRIM, ACTION_TRIM, trim) \ + X(EXPORT, ACTION_EXPORT, export_open) \ + X(PACK, ACTION_PACK, pack_open) \ + X(SAVE, ACTION_SAVE, save) \ + X(CUT, ACTION_CUT, cut) \ + X(COPY, ACTION_COPY, copy) \ + X(PASTE, ACTION_PASTE, paste) + + enum WindowFlagIndex + { +#define X(symbol, action, command) WINDOW_INDEX_##symbol, + WINDOW_FLAGS +#undef X + WINDOW_INDEX_COUNT + }; + enum WindowFlag { - WINDOW_ADD = 1 << 0, - WINDOW_REMOVE = 1 << 1, - WINDOW_REMOVE_UNUSED = 1 << 2, - WINDOW_DUPLICATE = 1 << 3, - WINDOW_MERGE = 1 << 4, - WINDOW_DEFAULT = 1 << 5, - WINDOW_CUT = 1 << 6, - WINDOW_COPY = 1 << 7, - WINDOW_PASTE = 1 << 8, - WINDOW_RENAME = 1 << 9, - WINDOW_PROPERTIES = 1 << 10, - WINDOW_REFERENCE_ITALIC = 1 << 11, - WINDOW_GROUP = 1 << 12 +#define X(symbol, action, command) WINDOW_##symbol = 1 << WINDOW_INDEX_##symbol, + WINDOW_FLAGS +#undef X + WINDOW_REFERENCE_ITALIC = 1 << WINDOW_INDEX_COUNT }; using WindowFlags = int; + inline constexpr int WINDOW_GROUP_KEY_OFFSET = 2; + + constexpr int window_group_key_get(int groupId) { return -groupId - WINDOW_GROUP_KEY_OFFSET; } + constexpr int window_group_id_from_key_get(int key) { return -key - WINDOW_GROUP_KEY_OFFSET; } + constexpr bool is_window_group_key(int key) { return key <= -WINDOW_GROUP_KEY_OFFSET; } + + struct WindowCardImage + { + resource::Texture* texture{}; + glm::vec2 size{}; + glm::vec2 uvMin{}; + glm::vec2 uvMax{1.0f}; + bool isValid{}; + }; + constexpr bool window_flag_has(WindowFlags flags, WindowFlag flag) { return (flags & flag) != 0; } struct Window { using StorageGet = std::function; + using ContainerGet = std::function; + using IndexGet = std::function; using ElementGet = std::function; using ElementKeyGet = std::function; using RowLabelGet = std::function; @@ -48,11 +88,11 @@ namespace anm2ed::imgui using RenameFinish = std::function; using TooltipDraw = std::function; using RowDragDropUpdate = std::function; + using CardImageGet = std::function; using PropertiesOpen = std::function; using Command = std::function; - using IsAvailable = std::function; + using IsEnabled = std::function; using Update = std::function; - using RowsUpdate = std::function; StringType title{}; bool Settings::* isOpen{}; @@ -60,24 +100,21 @@ namespace anm2ed::imgui ElementType containerType{ElementType::UNKNOWN}; ElementType elementType{ElementType::UNKNOWN}; const char* childLabel{"##Window Child"}; - StringType addTooltip{}; - StringType duplicateTooltip{}; - StringType mergeTooltip{}; - StringType removeTooltip{}; - StringType removeUnusedTooltip{}; - StringType defaultTooltip{}; + std::map tooltips{}; + std::vector> footer{}; StringType addEdit{}; + StringType propertiesEdit{}; StringType renameEdit{}; StringType pasteEdit{}; StringType removeUnusedEdit{}; StringType deserializeFailedToast{}; StringType unavailableText{STRING_UNDEFINED}; + int cardLines{}; int newElementId{-1}; int scrollQueued{-1}; int renameQueued{-1}; int renameId{-1}; int editId{-1}; - int footerRows{-1}; RenameState renameState{RENAME_SELECTABLE}; std::string renameText{}; PopupHelper popup{STRING_UNDEFINED}; @@ -90,11 +127,12 @@ namespace anm2ed::imgui Element editElement{}; Dialog* dialog{}; WindowFlags flags{WINDOW_COPY | WINDOW_PASTE}; - bool isChildPaddingZero{}; bool isPreserveEditElementOnOpen{}; ImVec2 tooltipWindowPadding{}; ImVec2 tooltipItemSpacing{}; StorageGet storage_get{}; + ContainerGet container_get{}; + IndexGet insert_index_get{}; ElementGet element_get{}; ElementKeyGet element_key_get{}; RowLabelGet row_label_get{}; @@ -103,30 +141,15 @@ namespace anm2ed::imgui RenameFinish rename_finish{}; TooltipDraw tooltip_draw{}; RowDragDropUpdate row_drag_drop_update{}; + CardImageGet card_image_get{}; PropertiesOpen properties_open{}; - Command add{}; - Command remove{}; - Command duplicate{}; - Command merge{}; +#define X(symbol, action, command) Command command{}; + WINDOW_FLAGS +#undef X Command merge_open{}; - Command group{}; - Command default_set{}; - Command cut{}; - Command copy{}; - Command paste{}; - Command reload{}; - Command replace{}; - Command save{}; - Command pack{}; - Command trim{}; - Command properties{}; - Command open{}; - Command path_set{}; - IsAvailable is_available{}; - Update begin_update{}; - RowsUpdate rows_update{}; - Update context_update{}; - Update footer_update{}; + std::map enabled{}; + IsEnabled is_available{}; + Update rows_update{}; Update body_update{}; Update popup_update{}; Update post_update{}; @@ -140,4 +163,32 @@ namespace anm2ed::imgui Window nulls_window_register(); Window events_window_register(); void window_update(Window&, Manager&, Settings&, Resources&, Dialog&, Clipboard&); + + enum class PopupButton + { + NONE, + CONFIRM, + CANCEL + }; + + inline constexpr auto DRAG_DROP_SOURCE_FLAGS = + ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers; + inline constexpr ImVec4 CARD_TINT_INVALID = ImVec4(1.0f, 0.25f, 0.25f, 1.0f); + inline constexpr ImVec4 CARD_TINT_VALID = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + + bool is_drag_drop_active(); + Element* window_container_get(const Window&, Document&); + Element* window_element_get(const Window&, Document&, int); + void window_element_apply_push(Window&, Manager&, const Element&, int); + void window_edit(Document&, Document::ChangeType, const std::string&, const std::function&); + void window_command_push(Window&, Manager&, Settings&, Clipboard&, const Window::Command&); + int window_selection_start(Window&, Document&, const std::vector&); + void window_selection_finish(Window&, Manager&, Settings&, Clipboard&, Document&, int); + bool window_row_draw(Window&, Manager&, Resources&, Document&, Element&, int, int, int); + void window_cards_draw(Window&, Manager&, Settings&, Resources&, Clipboard&, Document&, Element*); + void window_tooltip_name_draw(Resources&, const std::string&); + void window_tooltip_image_draw(const WindowCardImage&, const std::function&); + void window_directory_open(Dialog&, Document&, const std::filesystem::path&); + std::filesystem::path window_asset_path_get(Document&, const std::filesystem::path&); + PopupButton window_popup_buttons_draw(Manager&, const char*, bool = true, StringType = BASIC_CANCEL); } diff --git a/src/manager.cpp b/src/manager.cpp index 1ecb536..4d4ff2a 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -224,59 +224,15 @@ namespace anm2ed if (auto document = get()) document->change(Document::ALL); } - void Manager::layer_properties_open(int id) + void Manager::item_properties_open(ElementType type, int id) { - if (auto document = get(); document) - { - if (id == -1) - editLayer = element_make(ElementType::LAYER_ELEMENT); - else if (auto layer = document->anm2.element_get(ElementType::LAYER_ELEMENT, id); layer) - editLayer = *layer; - else - return; - - document->layer.reference = id; - - layerPropertiesPopup.open(); - } - } - - void Manager::layer_properties_trigger() { layerPropertiesPopup.trigger(); } - - void Manager::layer_properties_end() { layerPropertiesPopup.end(); } - - void Manager::layer_properties_close() - { - editLayer = element_make(ElementType::LAYER_ELEMENT); - layerPropertiesPopup.close(); - } - - void Manager::null_properties_open(int id) - { - if (auto document = get(); document) - { - auto nulls = document->anm2.element_get(ElementType::NULLS); - if (id == -1) - editNull = element_make(ElementType::NULL_ELEMENT); - else if (auto null = nulls ? child_id_get(*nulls, ElementType::NULL_ELEMENT, id) : nullptr; null) - editNull = *null; - else - return; - - document->null.reference = id; - - nullPropertiesPopup.open(); - } - } - - void Manager::null_properties_trigger() { nullPropertiesPopup.trigger(); } - - void Manager::null_properties_end() { nullPropertiesPopup.end(); } - - void Manager::null_properties_close() - { - editNull = element_make(ElementType::NULL_ELEMENT); - nullPropertiesPopup.close(); + auto document = get(); + auto row = track_container_get(type); + auto element = id == -1 || !document ? nullptr : document->anm2.element_get(type, id); + if (!document || !row || (id != -1 && !element)) return; + itemEdit = element ? *element : element_make(type); + (type == ElementType::LAYER_ELEMENT ? document->layer : document->null).reference = id; + itemPropertiesPopups[row - TRACK_CONTAINERS].open(); } void Manager::recent_files_trim() diff --git a/src/manager.hpp b/src/manager.hpp index 8128018..f00fb21 100644 --- a/src/manager.hpp +++ b/src/manager.hpp @@ -62,12 +62,9 @@ namespace anm2ed std::filesystem::path spritesheetDragDropPath{}; bool isSpritesheetDragDrop{}; - Element editLayer{element_make(ElementType::LAYER_ELEMENT)}; - imgui::PopupHelper layerPropertiesPopup{ - imgui::PopupHelper(LABEL_MANAGER_LAYER_PROPERTIES, imgui::POPUP_SMALL_NO_HEIGHT)}; - - Element editNull{element_make(ElementType::NULL_ELEMENT)}; - imgui::PopupHelper nullPropertiesPopup{ + Element itemEdit{}; + imgui::PopupHelper itemPropertiesPopups[std::size(TRACK_CONTAINERS)]{ + imgui::PopupHelper(LABEL_MANAGER_LAYER_PROPERTIES, imgui::POPUP_SMALL_NO_HEIGHT), imgui::PopupHelper(LABEL_MANAGER_NULL_PROPERTIES, imgui::POPUP_SMALL_NO_HEIGHT)}; Element makeRegion{element_make(ElementType::REGION)}; @@ -93,14 +90,7 @@ namespace anm2ed void autosave_file_clear(int); void set(int); void close(int); - void layer_properties_open(int = -1); - void layer_properties_trigger(); - void layer_properties_end(); - void layer_properties_close(); - void null_properties_open(int = -1); - void null_properties_trigger(); - void null_properties_end(); - void null_properties_close(); + void item_properties_open(ElementType, int = -1); void recent_files_load(); void recent_files_write(); diff --git a/src/util/vector.hpp b/src/util/vector.hpp index 12fa952..fd48c25 100644 --- a/src/util/vector.hpp +++ b/src/util/vector.hpp @@ -12,7 +12,7 @@ namespace anm2ed::util::vector return index >= 0 && index < (int)v.size() ? &v[index] : nullptr; } - template int find_index(std::vector& v, T& value) + template int find_index(const std::vector& v, const T& value) { auto it = std::find(v.begin(), v.end(), value); if (it == v.end()) return -1; @@ -86,8 +86,8 @@ namespace anm2ed::util::vector return moveIndices; } - template std::set move_indices_to_position(std::vector& v, const std::vector& indices, - int insertPos) + template + std::set move_indices_to_position(std::vector& v, const std::vector& indices, int insertPos) { if (indices.empty()) return {};