From d08f59d7ba3a73d414020ee376dd905bac03d6ca Mon Sep 17 00:00:00 2001 From: shweet Date: Sat, 3 Oct 2026 17:47:21 -0400 Subject: [PATCH] Stage 8a: panels as plain functions; content selection on the uid Selection - New panel kit (imgui/window/panel.*): list/card drawing with multi-select, rename, arrow keys, drag hooks and tooltips; a list panel helper for the context menu, shortcuts and footer; panels build their Actions inline. - Layers, nulls, events, sounds, spritesheets, regions, shaders and animations are plain functions over a small persistent state struct. - Content items are selected by uid in the shared Selection (one kind per content type, plus a focus per kind); regions are those of the focused spritesheet. Selection survives undo, paste and removal like the timeline's. - Combo labels are computed when drawn (Document::choices_get). - Deletes the Window callback framework, WINDOW_FLAGS, Storage and the per-window selection snapshot fields. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 2 +- src/document.cpp | 112 ++- src/document.hpp | 16 +- src/imgui/dockspace.cpp | 38 +- src/imgui/dockspace.hpp | 20 +- src/imgui/popup/item_properties.cpp | 7 +- src/imgui/window/animations.cpp | 944 +++++++++--------- src/imgui/window/frame_properties.cpp | 18 +- src/imgui/window/items.cpp | 309 +++--- src/imgui/window/panel.cpp | 353 +++++++ src/imgui/window/panel.hpp | 215 ++++ src/imgui/window/regions.cpp | 634 ++++++------ src/imgui/window/shaders.cpp | 289 ++---- src/imgui/window/shaders.hpp | 14 +- src/imgui/window/sounds.cpp | 234 ++--- src/imgui/window/spritesheet_editor.cpp | 17 +- src/imgui/window/spritesheets.cpp | 610 ++++++----- src/imgui/window/timeline/context.hpp | 3 +- src/imgui/window/timeline/frames.cpp | 7 +- src/imgui/window/timeline/menus.cpp | 4 +- src/imgui/window/timeline/popups.cpp | 2 +- src/imgui/window/timeline/selection.cpp | 4 +- src/imgui/window/timeline/timeline.cpp | 2 +- src/imgui/window/window.cpp | 578 ----------- src/imgui/window/window.hpp | 282 ------ .../wizard/change_all_frame_properties.cpp | 19 +- src/manager.cpp | 5 +- src/manager.hpp | 1 + src/selection.cpp | 65 +- src/selection.hpp | 16 +- src/snapshots.cpp | 8 - src/snapshots.hpp | 9 - src/storage.cpp | 19 - src/storage.hpp | 27 - src/util/imgui/input.cpp | 17 +- src/util/imgui/input.hpp | 10 +- tests/selection.cpp | 23 + 37 files changed, 2355 insertions(+), 2578 deletions(-) create mode 100644 src/imgui/window/panel.cpp create mode 100644 src/imgui/window/panel.hpp delete mode 100644 src/imgui/window/window.cpp delete mode 100644 src/imgui/window/window.hpp delete mode 100644 src/storage.cpp delete mode 100644 src/storage.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c84e5b5..523c5b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -108,7 +108,7 @@ file(GLOB PROJECT_SRC CONFIGURE_DEPENDS set(CORE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) file(GLOB CORE_SRC CONFIGURE_DEPENDS ${CORE_DIR}/edit/*.cpp ${CORE_DIR}/model/*.cpp) foreach(CORE_FILE log resource/strings resource/image resource/audio_data resource/asset_store util/file util/path util/math util/string util/time util/working_directory - util/xml util/pack util/imgui/multiselect snapshots storage playback selection) + util/xml util/pack util/imgui/multiselect snapshots playback selection) list(APPEND CORE_SRC ${CORE_DIR}/${CORE_FILE}.cpp) endforeach() list(REMOVE_ITEM PROJECT_SRC ${CORE_SRC}) diff --git a/src/document.cpp b/src/document.cpp index af274ad..582ce09 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -109,26 +109,6 @@ namespace anm2ed::document return false; } - template - void storage_labels_set(Storage& storage, const Items& items, bool isNone, Label&& label_get) - { - std::vector labels{}; - std::vector ids{}; - if (isNone) - { - labels.emplace_back(localize.get(BASIC_NONE)); - ids.emplace_back(-1); - } - for (const auto& item : items) - { - labels.emplace_back(label_get(item)); - ids.emplace_back(item.id); - } - storage.labels_set(std::move(labels), std::move(ids)); - } - - std::string item_name_get(const auto& item) { return item.name; } - // Loads assets for elements that are new or whose path changed, and forgets those of removed elements. template void resources_sync(Document& document, const Items& items, std::map& keys, @@ -633,26 +613,7 @@ namespace anm2ed hash_set(); assets_sync(); - auto path_label_get = [](StringType format) - { - return [format](const auto& item) - { - auto pathString = path::to_utf8(item.path); - return std::vformat(localize.get(format), std::make_format_args(item.id, pathString)); - }; - }; - - auto& content = model.content; - document::storage_labels_set(event, content.events, true, [](const auto& item) { return item.name; }); - document::storage_labels_set(spritesheet, content.spritesheets, false, path_label_get(FORMAT_SPRITESHEET)); spritesheet_hashes_sync(); - regionBySpritesheet.clear(); - for (auto& element : content.spritesheets) - document::storage_labels_set(regionBySpritesheet[element.id], element.regions, true, - [](const auto& item) { return item.name; }); - document::storage_labels_set(shader, content.shaders, true, [](const auto& item) { return item.name; }); - document::storage_labels_set(sound, content.sounds, true, path_label_get(FORMAT_SOUND)); - snapshots.commit(); index = model::UidIndex(model); } @@ -730,6 +691,62 @@ namespace anm2ed selection_references_set(selection, model, kind, references); } + std::set Document::selected_ids_get(SelectionKind kind) const + { + return selection_ids_get(selection, model, kind); + } + + void Document::selected_ids_set(SelectionKind kind, const std::set& ids) + { + selection_ids_set(selection, model, kind, ids); + } + + int Document::focused_id_get(SelectionKind kind) const { return selection_focus_id_get(selection, model, kind); } + + void Document::focused_id_set(SelectionKind kind, int id) { selection_focus_id_set(selection, model, kind, id); } + + void Document::selected_clear(SelectionKind kind) + { + selection.uids.erase(kind); + selection.focuses.erase(kind); + } + + // Combo entries for a content kind (regions are those of layer `layerId`'s spritesheet); all but spritesheets start with None. + Choices Document::choices_get(SelectionKind kind, int layerId) const + { + Choices choices{}; + if (kind != SelectionKind::SPRITESHEETS) + { + choices.ids.push_back(-1); + choices.labels.emplace_back(localize.get(BASIC_NONE)); + } + auto add = [&](const auto& items, auto&& label_get) + { + for (const auto& item : items) + { + choices.ids.push_back(item.id); + choices.labels.push_back(label_get(item)); + } + }; + auto name_get = [](const auto& item) { return item.name; }; + auto path_label_get = [](StringType format) + { + return [format](const auto& item) + { + auto pathString = path::to_utf8(item.path); + return std::vformat(localize.get(format), std::make_format_args(item.id, pathString)); + }; + }; + auto& content = model.content; + if (kind == SelectionKind::SPRITESHEETS) add(content.spritesheets, path_label_get(FORMAT_SPRITESHEET)); + if (kind == SelectionKind::SOUNDS) add(content.sounds, path_label_get(FORMAT_SOUND)); + if (kind == SelectionKind::EVENTS) add(content.events, name_get); + if (kind == SelectionKind::SHADERS) add(content.shaders, name_get); + if (kind == SelectionKind::REGIONS) + if (auto spritesheet = model.layer_spritesheet_get(layerId)) add(spritesheet->regions, name_get); + return choices; + } + std::set Document::animations_selected_get() const { std::set indices{}; @@ -810,18 +827,11 @@ namespace anm2ed return result; } - Storage* Document::layer_regions_get(int layerId) - { - auto layer = model::item_get(model.content.layers, layerId); - auto regions = layer ? regionBySpritesheet.find(layer->spritesheetId) : regionBySpritesheet.end(); - return regions == regionBySpritesheet.end() ? nullptr : ®ions->second; - } - const model::Frame* Document::frame_get() const { return model.frame_get(reference_get()); } const model::Track* Document::item_get() const { return model.track_get(reference_get()); } const model::Spritesheet* Document::spritesheet_get() const { - return model::item_get(model.content.spritesheets, spritesheet.reference); + return model::item_get(model.content.spritesheets, focused_id_get(SelectionKind::SPRITESHEETS)); } void Document::spritesheets_add(const std::vector& paths) @@ -855,11 +865,11 @@ namespace anm2ed texture_set(element.id, std::move(texture)); texturePaths[element.id] = element.path; added.insert(element.id); - spritesheet.reference = element.id; spritesheet_hash_set_saved(element.id); toast_log(Level::INFO, TOAST_SPRITESHEET_INITIALIZED, element.id, path::to_utf8(element.path)); } - spritesheet.selection = added; + selected_ids_set(SelectionKind::SPRITESHEETS, added); + focused_id_set(SelectionKind::SPRITESHEETS, *added.rbegin()); change(); } @@ -881,10 +891,10 @@ namespace anm2ed sound_set(element.id, resource::AudioData(path::case_insensitive_find(element.path))); soundPaths[element.id] = element.path; added.insert(element.id); - sound.reference = element.id; toast_log(Level::INFO, TOAST_SOUND_INITIALIZED, element.id, path::to_utf8(element.path)); } - sound.selection = added; + selected_ids_set(SelectionKind::SOUNDS, added); + focused_id_set(SelectionKind::SOUNDS, *added.rbegin()); change(); } diff --git a/src/document.hpp b/src/document.hpp index 785c594..1779c2f 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -26,13 +26,18 @@ namespace anm2ed class Manager; struct Command; + // Ids and labels for a combo box of content items. + struct Choices + { + std::vector ids{}; + std::vector labels{}; + }; + struct DocumentData { std::filesystem::path path{}; uint64_t tabId{}; Snapshots snapshots{}; - std::map regionBySpritesheet{}; - Storage animation{}; resource::AssetStore assets{}; std::map textureDrafts{}; int changeAllFramePropertiesRegionId{-1}; @@ -146,6 +151,12 @@ namespace anm2ed void reference_set(Reference); std::set selected_get(SelectionKind) const; void selected_set(SelectionKind, const std::set&); + std::set selected_ids_get(SelectionKind) const; + void selected_ids_set(SelectionKind, const std::set&); + int focused_id_get(SelectionKind) const; + void focused_id_set(SelectionKind, int); + void selected_clear(SelectionKind); + Choices choices_get(SelectionKind, int = -1) const; std::set animations_selected_get() const; void animations_selected_set(const std::set&); std::set item_frame_references_get(Reference) const; @@ -155,7 +166,6 @@ namespace anm2ed void frame_references_clear(); std::vector layer_references_get(); - Storage* layer_regions_get(int); const model::Frame* frame_get() const; const model::Track* item_get() const; const model::Spritesheet* spritesheet_get() const; diff --git a/src/imgui/dockspace.cpp b/src/imgui/dockspace.cpp index f72f3a1..2ac4bf4 100644 --- a/src/imgui/dockspace.cpp +++ b/src/imgui/dockspace.cpp @@ -32,19 +32,41 @@ namespace anm2ed::imgui { if (ImGui::DockSpace(ImGui::GetID("##DockSpace"), ImVec2(), ImGuiDockNodeFlags_PassthruCentralNode)) { + auto panel_make = [&](PanelState& state) + { return Panel{manager, settings, resources, dialog, clipboard, *document, state}; }; + auto panel_update = [&](PanelState& state, void (*update)(Panel&)) + { + auto panel = panel_make(state); + update(panel); + }; if (settings.windowIsAnimationPreview) animationPreview.update(manager, settings, resources); - if (settings.windowIsAnimations) window_update(animations, manager, settings, resources, dialog, clipboard); - if (settings.windowIsRegions) window_update(regions, manager, settings, resources, dialog, clipboard); - if (settings.windowIsEvents) window_update(events, manager, settings, resources, dialog, clipboard); + if (settings.windowIsAnimations) + { + auto panel = panel_make(animations.state); + animations_update(panel, animations); + } + if (settings.windowIsRegions) + { + auto panel = panel_make(regions.state); + regions_update(panel, regions); + } + if (settings.windowIsEvents) panel_update(events, events_update); if (settings.windowIsFrameProperties) frameProperties.update(manager, settings); - if (settings.windowIsLayers) window_update(layers, manager, settings, resources, dialog, clipboard); - if (settings.windowIsNulls) window_update(nulls, manager, settings, resources, dialog, clipboard); + if (settings.windowIsLayers) panel_update(layers, layers_update); + if (settings.windowIsNulls) panel_update(nulls, nulls_update); if (settings.windowIsOnionskin) onionskin.update(manager, settings); - if (settings.windowIsShaders) shaders.update(manager, settings, resources, dialog); - if (settings.windowIsSounds) window_update(sounds, manager, settings, resources, dialog, clipboard); + if (settings.windowIsShaders) + { + auto panel = panel_make(shaders.state); + shaders_update(panel, shaders); + } + if (settings.windowIsSounds) panel_update(sounds, sounds_update); if (settings.windowIsSpritesheetEditor) spritesheetEditor.update(manager, settings, resources); if (settings.windowIsSpritesheets) - window_update(spritesheets, manager, settings, resources, dialog, clipboard); + { + auto panel = panel_make(spritesheets.state); + spritesheets_update(panel, spritesheets); + } if (settings.windowIsTimeline) timeline.update(manager, settings, resources, clipboard); if (settings.windowIsTools) tools.update(manager, settings, resources); isCanvasFocused = (settings.windowIsAnimationPreview && animationPreview.is_focused_get()) || diff --git a/src/imgui/dockspace.hpp b/src/imgui/dockspace.hpp index b1e8287..4069451 100644 --- a/src/imgui/dockspace.hpp +++ b/src/imgui/dockspace.hpp @@ -1,17 +1,17 @@ #pragma once -#include "popup/autosave_restore.hpp" #include "documents.hpp" +#include "popup/autosave_restore.hpp" #include "taskbar.hpp" #include "window/animation_preview.hpp" #include "window/frame_properties.hpp" #include "window/onionskin.hpp" +#include "window/panel.hpp" #include "window/shaders.hpp" #include "window/spritesheet_editor.hpp" #include "window/timeline/timeline.hpp" #include "window/tools.hpp" #include "window/welcome.hpp" -#include "window/window.hpp" namespace anm2ed::imgui { @@ -19,17 +19,17 @@ namespace anm2ed::imgui { AnimationPreview animationPreview; bool isCanvasFocused{}; - Window animations{animations_window_register()}; - Window regions{regions_window_register()}; - Window events{events_window_register()}; + AnimationsPanel animations{}; + RegionsPanel regions{}; + PanelState events{}; FrameProperties frameProperties; - Window layers{layers_window_register()}; - Window nulls{nulls_window_register()}; + PanelState layers{}; + PanelState nulls{}; Onionskin onionskin; - ShadersWindow shaders; + ShadersPanel shaders{}; SpritesheetEditor spritesheetEditor; - Window spritesheets{spritesheets_window_register()}; - Window sounds{sounds_window_register()}; + SpritesheetsPanel spritesheets{}; + PanelState sounds{}; Timeline timeline; Tools tools; Welcome welcome; diff --git a/src/imgui/popup/item_properties.cpp b/src/imgui/popup/item_properties.cpp index 580c03b..0cbe08b 100644 --- a/src/imgui/popup/item_properties.cpp +++ b/src/imgui/popup/item_properties.cpp @@ -119,8 +119,9 @@ namespace anm2ed::imgui::popup ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); if (type == LAYER) { - combo_id_mapped(localize.get(LABEL_SPRITESHEET), &addItemSpritesheetID, document.spritesheet.ids, - document.spritesheet.labels); + auto spritesheets = document.choices_get(SelectionKind::SPRITESHEETS); + combo_id_mapped(localize.get(LABEL_SPRITESHEET), &addItemSpritesheetID, spritesheets.ids, + spritesheets.labels); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SPRITESHEET)); } else if (type == NULL_) @@ -213,7 +214,7 @@ namespace anm2ed::imgui::popup document.frame_references_clear(); if (queuedType == LAYER) if (auto layer = model::item_get(document.model.content.layers, addId)) - document.spritesheet.reference = layer->spritesheetId; + document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); } }}); diff --git a/src/imgui/window/animations.cpp b/src/imgui/window/animations.cpp index 66d09ed..2ebe5d5 100644 --- a/src/imgui/window/animations.cpp +++ b/src/imgui/window/animations.cpp @@ -1,10 +1,9 @@ -#include "window.hpp" +#include "panel.hpp" #include #include #include -#include "toast.hpp" #include "util/imgui/draw.hpp" #include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" @@ -20,6 +19,12 @@ namespace anm2ed::imgui constexpr int MERGE_OPTIONS_ROWS = 2; constexpr float MERGE_OPTIONS_HALF = 0.5f; constexpr int MERGE_POPUP_CHILD_COUNT = 3; + constexpr int GROUP_KEY_OFFSET = 2; + + // Animation groups share the key space with animation indices as negative keys. + constexpr int group_key_get(int groupId) { return -groupId - GROUP_KEY_OFFSET; } + constexpr int group_id_from_key_get(int key) { return -key - GROUP_KEY_OFFSET; } + constexpr bool is_group_key(int key) { return key <= -GROUP_KEY_OFFSET; } enum class AnimationDropZone { @@ -28,15 +33,9 @@ namespace anm2ed::imgui AFTER }; - enum class AnimationDragDropType - { - ANIMATION, - GROUP - }; - struct AnimationDragDropItem { - AnimationDragDropType type{AnimationDragDropType::ANIMATION}; + bool isGroup{}; int id{-1}; bool operator==(const AnimationDragDropItem&) const = default; @@ -77,9 +76,18 @@ namespace anm2ed::imgui return first; } - // The list draws from Storage/Window mirrors of the document Selection: loaded each frame, written back on change. - void animations_selection_set(Window& window, Document& document, const std::set& indices, - const std::set& groupIds) + std::set animation_groups_selected_get(const Document& document) + { + std::set groupIds{}; + auto uids = document.selection.uids.find(SelectionKind::ANIMATION_GROUPS); + if (uids == document.selection.uids.end()) return groupIds; + for (const auto& entry : document.model.animations.entries) + if (auto group = std::get_if(&entry); group && uids->second.contains(group->uid)) + groupIds.insert(group->id); + return groupIds; + } + + void animations_selection_set(Document& document, const std::set& indices, const std::set& groupIds) { document.animations_selected_set(indices); auto& groupUids = document.selection.uids[SelectionKind::ANIMATION_GROUPS]; @@ -87,34 +95,21 @@ namespace anm2ed::imgui for (const auto& entry : document.model.animations.entries) if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) groupUids.insert(group->uid); - document.animation.selection = indices; - window.selection = groupIds; } - void animations_selection_load(Window& window, Document& document) + // Selected animations plus every animation of a selected group. + std::set animation_selected_indices_get(const Document& document) { - document.animation.selection = document.animations_selected_get(); - window.selection.clear(); - auto& groupUids = document.selection.uids[SelectionKind::ANIMATION_GROUPS]; - for (const auto& entry : document.model.animations.entries) - if (auto group = std::get_if(&entry); group && groupUids.contains(group->uid)) - window.selection.insert(group->id); - } - - std::set animation_selected_indices_get(Document& document, const Window& window) - { - std::set result(document.animation.selection.begin(), document.animation.selection.end()); - for (auto groupId : window.selection) + auto result = document.animations_selected_get(); + for (auto groupId : animation_groups_selected_get(document)) result.merge(edit::animation_group_indices_get(document.model, groupId)); return result; } - std::vector animation_groupable_indices_get(Document& document) + std::vector animation_groupable_indices_get(const Document& document) { - auto& selection = document.animation.selection; - if (selection.empty()) return {}; std::vector result{}; - for (auto index : selection) + for (auto index : document.animations_selected_get()) { if (!document.model.animation_get(index) || document.model.animation_group_id_get(index) != -1) return {}; result.push_back(index); @@ -122,14 +117,14 @@ namespace anm2ed::imgui return result; } - std::set animation_merge_indices_get(Document& document, const std::set& keys, int reference) + std::set animation_merge_indices_get(const Document& document, const std::set& keys, int reference) { std::set result{}; for (auto key : keys) - if (!is_window_group_key(key)) + if (!is_group_key(key)) result.insert(key); else - result.merge(edit::animation_group_indices_get(document.model, window_group_id_from_key_get(key))); + result.merge(edit::animation_group_indices_get(document.model, group_id_from_key_get(key))); result.erase(reference); return result; } @@ -142,15 +137,15 @@ namespace anm2ed::imgui document.overlayDocumentId = 0; } - void animations_erase(Window& window, Document& document, const std::set& indices, const std::set& groupIds, + void animations_erase(Document& document, const std::set& indices, const std::set& groupIds, StringType label) { document.edit_apply(label, - [&](model::Model& anm2) + [&](model::Model& model) { animation_overlay_reset(document, indices); - animations_selection_set(window, document, {}, {}); - return edit::animations_remove(anm2, indices, groupIds); + animations_selection_set(document, {}, {}); + return edit::animations_remove(model, indices, groupIds); }); } @@ -162,59 +157,59 @@ namespace anm2ed::imgui return indices; } - std::string animation_clipboard_text_get(Document& document, const Window& window) + std::string animation_clipboard_text_get(const Document& document) { std::string clipboardText{}; auto& model = document.model; + auto groupIds = animation_groups_selected_get(document); + auto selection = document.animations_selected_get(); for (const auto& entry : model.animations.entries) - if (auto group = std::get_if(&entry); group && window.selection.contains(group->id)) + if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) clipboardText += model::animation_group_to_string(*group); for (int i = 0; i < model.animations_count_get(); ++i) { auto groupId = model.animation_group_id_get(i); - if (document.animation.selection.contains(i) || window.selection.contains(groupId)) + if (selection.contains(i) || groupIds.contains(groupId)) clipboardText += model::animation_to_string(*model.animation_get(i), groupId); } return clipboardText; } - void animations_insert(Window& window, Document& document, const std::string& text, int start, int targetGroupId, + void animations_insert(PanelState& state, Document& document, const std::string& text, int start, int targetGroupId, StringType edit) { std::set groupIds{}; std::string errorString{}; - auto uids = document.edit_apply( - edit, - [&](model::Model& anm2) - { - auto uids = edit::animations_paste(anm2, text, start, targetGroupId, groupIds, &errorString); - if (uids.empty()) return uids; - auto indices = animation_indices_get(document, uids); - animations_selection_set(window, document, groupIds.empty() ? indices : std::set{}, groupIds); - document.reference_set({}); - window.newElementId = -1; - if (indices.empty()) return uids; - window.scrollQueued = *indices.rbegin(); - if (!groupIds.empty()) return uids; - document.reference_set({*indices.rbegin()}); - if (indices.size() == 1) window.newElementId = *indices.rbegin(); - return uids; - }); + document.edit_apply(edit, + [&](model::Model& model) + { + auto uids = edit::animations_paste(model, text, start, targetGroupId, groupIds, &errorString); + if (uids.empty()) return uids; + auto indices = animation_indices_get(document, uids); + animations_selection_set(document, groupIds.empty() ? indices : std::set{}, groupIds); + document.reference_set({}); + if (indices.empty()) return uids; + state.scrollId = *indices.rbegin(); + if (!groupIds.empty()) return uids; + document.reference_set({*indices.rbegin()}); + if (indices.size() == 1) state.newId = *indices.rbegin(); + return uids; + }); if (!errorString.empty()) toast_log(Level::ERROR, TOAST_DESERIALIZE_ANIMATIONS_FAILED, errorString); } - int animations_merge(Document& document, const AnimationMergeOptions& options, - const std::set* quickSelection = nullptr, - const std::set* quickGroupSelection = nullptr) + // Merges into options.reference; without a merge-popup selection, the selected animations merge into the first. + int animations_merge(Document& document, const AnimationMergeOptions& options) { + auto isQuick = options.selection.empty(); auto target = options.reference; - auto sources = - options.selection.empty() ? *quickSelection : animation_merge_indices_get(document, options.selection, target); - auto type = options.selection.empty() ? merge::APPEND : options.type; - auto isDeleteAfter = options.selection.empty() || options.isDeleteAnimationsAfter; - auto ungroupIds = options.selection.empty() && quickGroupSelection ? *quickGroupSelection : std::set{}; + auto sources = isQuick ? animation_selected_indices_get(document) + : animation_merge_indices_get(document, options.selection, target); + auto type = isQuick ? merge::APPEND : options.type; + auto isDeleteAfter = isQuick || options.isDeleteAnimationsAfter; + auto ungroupIds = isQuick ? animation_groups_selected_get(document) : std::set{}; - if (options.selection.empty()) + if (isQuick) { auto count = document.model.animations_count_get(); if (sources.empty()) return -1; @@ -228,14 +223,14 @@ namespace anm2ed::imgui int merged{-1}; document.edit_apply(EDIT_MERGE_ANIMATIONS, - [&](model::Model& anm2) + [&](model::Model& model) { animation_overlay_reset(document, sources); - auto uids = edit::animations_merge(anm2, target, sources, type, isDeleteAfter, ungroupIds); + auto uids = edit::animations_merge(model, target, sources, type, isDeleteAfter, ungroupIds); auto indices = animation_indices_get(document, uids); if (indices.empty()) return uids; merged = *indices.begin(); - document.animations_selected_set({merged}); + animations_selection_set(document, {merged}, {}); document.reference_set({merged}); return uids; }); @@ -251,45 +246,42 @@ namespace anm2ed::imgui return AnimationDropZone::INSIDE; } - void animation_move_command_push(Window& window, Manager& manager, std::vector items, + void animation_move_command_push(const Panel& panel, std::vector items, edit::AnimationTarget target) { if (items.empty()) return; - manager.command_push({manager.selected, [&window, items, target](Manager&, Document& document) - { - std::set indices{}; - std::set groupIds{}; - for (auto item : items) - (item.type == AnimationDragDropType::GROUP ? groupIds : indices).insert(item.id); - document.edit_apply(EDIT_MOVE_ANIMATIONS, - [&](model::Model& model) - { - auto uids = edit::animations_move(model, indices, groupIds, target); - if (uids.empty() && groupIds.empty()) return; - animations_selection_set(window, document, - animation_indices_get(document, uids), - groupIds); - }); - }}); + command_push(panel, + [items, target](Document& document) + { + std::set indices{}; + std::set groupIds{}; + for (auto item : items) + (item.isGroup ? groupIds : indices).insert(item.id); + document.edit_apply(EDIT_MOVE_ANIMATIONS, + [&](model::Model& model) + { + auto uids = edit::animations_move(model, indices, groupIds, target); + if (uids.empty() && groupIds.empty()) return; + animations_selection_set(document, animation_indices_get(document, uids), + groupIds); + }); + }); } - void animation_drag_drop_source_update(Document& document, const Window& window, AnimationDragDropItem fallback) + void animation_drag_drop_source_update(const Document& document, AnimationDragDropItem fallback) { if (!ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) return; static std::vector items{}; items.clear(); - auto isFallbackSelected = fallback.type == AnimationDragDropType::GROUP - ? window.selection.contains(fallback.id) - : document.animation.selection.contains(fallback.id); - if (isFallbackSelected) + auto groupIds = animation_groups_selected_get(document); + auto selection = document.animations_selected_get(); + if (fallback.isGroup ? groupIds.contains(fallback.id) : selection.contains(fallback.id)) { - auto groupIds = edit::animation_group_ids_get(document.model); - for (auto groupId : window.selection) - if (groupIds.contains(groupId)) items.push_back({AnimationDragDropType::GROUP, groupId}); - for (auto animationIndex : document.animation.selection) - if (document.model.animation_get(animationIndex)) - items.push_back({AnimationDragDropType::ANIMATION, animationIndex}); + for (auto groupId : groupIds) + items.push_back({true, groupId}); + for (auto index : selection) + if (document.model.animation_get(index)) items.push_back({false, index}); } if (items.empty() && fallback.id >= 0) items.push_back(fallback); ImGui::SetDragDropPayload(ANIMATION_DRAG_DROP, items.data(), items.size() * sizeof(AnimationDragDropItem)); @@ -305,7 +297,7 @@ namespace anm2ed::imgui return {items, items + payload->DataSize / sizeof(AnimationDragDropItem)}; } - bool animation_group_drag_drop_update(Window& window, Manager& manager, int groupId, ImVec2 itemMin, ImVec2 itemMax) + bool animation_group_drag_drop_update(const Panel& panel, int groupId, ImVec2 itemMin, ImVec2 itemMax) { if (!ImGui::BeginDragDropTarget()) return false; auto items = animation_drag_drop_target_items_get(); @@ -313,8 +305,7 @@ namespace anm2ed::imgui 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 isGroupDragged = std::ranges::any_of(items, &AnimationDragDropItem::isGroup); auto isDropIntoGroup = dropZone == AnimationDropZone::INSIDE && !isGroupDragged; if (isDropIntoGroup) drop_box_draw(ImGui::GetWindowDrawList(), itemMin, itemMax); @@ -324,16 +315,16 @@ namespace anm2ed::imgui isDelivered = ImGui::GetDragDropPayload()->IsDelivery(); if (isDelivered) animation_move_command_push( - window, manager, items, + panel, items, {.groupId = groupId, .isAfter = dropZone != AnimationDropZone::BEFORE, .isInto = isDropIntoGroup}); } ImGui::EndDragDropTarget(); return isDelivered; } - bool animation_row_drag_drop_update(Window& window, Manager& manager, Document& document, int index, int) + bool animation_row_drag_drop_update(const Panel& panel, int index) { - animation_drag_drop_source_update(document, window, {AnimationDragDropType::ANIMATION, index}); + animation_drag_drop_source_update(panel.document, {false, index}); if (!ImGui::BeginDragDropTarget()) return false; auto items = animation_drag_drop_target_items_get(); @@ -345,44 +336,45 @@ namespace anm2ed::imgui 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, {.animationIndex = index, .isAfter = isDropAfter}); + if (isDelivered) animation_move_command_push(panel, items, {.animationIndex = index, .isAfter = isDropAfter}); } ImGui::EndDragDropTarget(); return isDelivered; } - void animation_group_set_push(Manager& manager, int groupId, StringType edit, std::optional name, + void animation_group_set_push(const Panel& panel, int groupId, StringType edit, std::optional name, std::optional isExpanded) { - manager.command_push({manager.selected, [groupId, edit, name, isExpanded](Manager&, Document& document) - { - auto first = animation_group_first_index_get(document.model, groupId); - auto group = document.model.animation_group_get(first); - if (!group || (name.value_or(group->name) == group->name && - isExpanded.value_or(group->isExpanded) == group->isExpanded)) - return; - document.edit_apply(edit, - [&](model::Model& model) - { - auto group = model.animation_group_edit(first); - group->name = name.value_or(group->name); - group->isExpanded = isExpanded.value_or(group->isExpanded); - }); - }}); + command_push(panel, + [groupId, edit, name, isExpanded](Document& document) + { + auto first = animation_group_first_index_get(document.model, groupId); + auto group = document.model.animation_group_get(first); + if (!group || (name.value_or(group->name) == group->name && + isExpanded.value_or(group->isExpanded) == group->isExpanded)) + return; + document.edit_apply(edit, + [&](model::Model& model) + { + auto group = model.animation_group_edit(first); + 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, - const model::AnimationGroup& group, int firstIndex, int arrowSelectionId, bool& isRowsDone) + // A group's tree node (renamable, a drop target) and, when expanded, its animations' rows. + bool animation_group_draw(Panel& panel, std::set& selection, std::set& groupSelection, int& focus, + const ListRows& rows, const model::AnimationGroup& group, int firstIndex, int arrowKey) { - auto& groupSelection = window.selection; - auto renameKey = window_group_key_get(group.id); - auto isRenaming = window.renameId == renameKey; - if (window.renameQueued == renameKey) + auto& state = panel.state; + auto key = group_key_get(group.id); + if (state.newId == key) { - window.renameState = RENAME_FORCE_EDIT; - window.renameQueued = -1; + state.renameState = RENAME_FORCE_EDIT; + state.newId = -1; } + auto isRenaming = state.renameId == key; ImGui::PushID("Animation Group"); ImGui::PushID(group.id); @@ -390,29 +382,28 @@ namespace anm2ed::imgui auto groupName = group.name; 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 : groupName, groupSelection.contains(group.id), - ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth, window.renameState); + std::format("###Document #{} Animation Group #{}", panel.manager.selected, group.id), + isRenaming ? state.renameText : groupName, groupSelection.contains(group.id), + ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth, state.renameState); auto itemMin = ImGui::GetItemRectMin(); auto itemMax = ImGui::GetItemRectMax(); if (tree.isRenameStarted) { - window.renameId = renameKey; - window.renameText = group.name; + state.renameId = key; + state.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 (isRenaming) animation_group_set_push(panel, group.id, EDIT_RENAME_GROUP, state.renameText, std::nullopt); + state.renameId = -1; + state.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); + animation_group_set_push(panel, 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) { @@ -425,374 +416,387 @@ namespace anm2ed::imgui groupSelection.insert(group.id); if (isDeselected ? selection.empty() && groupSelection.empty() : !isCtrl || selection.empty()) { - document.animation.reference = -1; - document.reference_set({}); - document.frame_references_clear(); + panel.document.reference_set({}); + panel.document.frame_references_clear(); } } - animation_drag_drop_source_update(document, window, {AnimationDragDropType::GROUP, group.id}); - isRowsDone = animation_group_drag_drop_update(window, manager, group.id, itemMin, itemMax); + animation_drag_drop_source_update(panel.document, {true, group.id}); + auto isRowsDone = animation_group_drag_drop_update(panel, group.id, itemMin, itemMax); if (tree.isOpen) { for (int i = 0; i < (int)group.animations.size() && !isRowsDone; ++i) - isRowsDone = - window_row_draw(window, manager, resources, document, firstIndex + i, firstIndex + i, arrowSelectionId); + isRowsDone = row_draw(panel, selection, focus, rows, firstIndex + i, firstIndex + i, arrowKey); ImGui::TreePop(); } ImGui::PopID(); ImGui::PopID(); + return isRowsDone; } - Window animations_window_register() + void animations_merge_popup_update(Panel& panel, AnimationsPanel& animations) { - Window window{}; - window.title = LABEL_ANIMATIONS_WINDOW; - window.isOpen = &Settings::windowIsAnimations; - 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.name_get = [](Document& document, int index) + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& popup = animations.mergePopup; + auto& mergeSelection = animations.mergeSelection; + auto mergeReference = animations.mergeReference; + + popup.trigger(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + + struct AnimationMergeCandidate { - auto animation = document.model.animation_get(index); - return animation ? animation->name : std::string{}; + int key{}; + std::string label{}; }; - window.rename_apply = [](Document&, model::Model& model, int index, const std::string& name) + std::vector candidates{}; + auto candidate_animation_push = [&](const model::Animation& animation, int animationIndex, bool isGrouped) { - auto animation = model.animation_edit(index); - if (!animation) return; - if (model.animations_count_get() == 1) model.animations.defaultAnimation = name; - animation->name = name; + if (animationIndex != mergeReference) + candidates.push_back({animationIndex, isGrouped ? std::format(" {}", animation.name) : animation.name}); }; - window.row_font_get = [](Document& document, int index) + animation_entries_each(document.model, + [&](int index, const model::Animation* animation, const model::AnimationGroup* group) + { + if (animation) return candidate_animation_push(*animation, index, false); + auto isReferenceOnly = group->animations.size() == 1 && index == mergeReference; + if (group->animations.empty() || isReferenceOnly) return; + candidates.push_back( + {group_key_get(group->id), + group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name}); + for (int i = 0; i < (int)group->animations.size(); ++i) + candidate_animation_push(*group->animations[i], index + i, true); + }); + + 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)) { - auto animation = document.model.animation_get(index); - auto isDefault = animation && document.model.animations.defaultAnimation == animation->name; - auto isReferenced = document.reference_get().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_set({index}); - document.frame_references_clear(); - }; - window.tooltip_draw = [](Document& document, Resources& resources, int index) - { - auto& animation = *document.model.animation_get(index); - window_tooltip_name_draw(resources, animation.name); - if (document.model.animations.defaultAnimation == animation.name) + animations.mergeKeys.clear(); + for (const auto& candidate : candidates) + animations.mergeKeys.push_back(candidate.key); + mergeSelection.set_index_map(&animations.mergeKeys); + mergeSelection.start(candidates.size()); + for (int i = 0; i < (int)candidates.size(); ++i) { - ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); - ImGui::TextUnformatted(localize.get(BASIC_DEFAULT)); - ImGui::PopFont(); + ImGui::PushID(candidates[i].key); + ImGui::SetNextItemSelectionUserData(i); + ImGui::Selectable(candidates[i].label.c_str(), mergeSelection.contains(candidates[i].key)); + ImGui::PopID(); } - 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) + mergeSelection.finish(); + mergeSelection.set_index_map(nullptr); + } + ImGui::EndChild(); + + if (ImGui::BeginChild("##Merge Options", optionsSize, ImGuiChildFlags_Borders)) { - auto& model = document.model; - auto groupIds = edit::animation_group_ids_get(model); - animations_selection_load(window, document); - - std::vector visibleIds{}; - window.order.clear(); - for (int i = 0; i < model.animations_count_get(); ++i) - window.order.push_back(i); - animation_entries_each(model, - [&](int index, const model::Animation* animation, const model::AnimationGroup* group) - { - if (animation) visibleIds.push_back(index); - if (group && group->isExpanded) - for (int i = 0; i < (int)group->animations.size(); ++i) - visibleIds.push_back(index + i); - }); - - auto arrowSelectionId = window_selection_start(window, document, visibleIds); - if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + auto size = ImVec2(optionsSize.x * MERGE_OPTIONS_HALF, optionsSize.y - ImGui::GetStyle().WindowPadding.y * 2); + if (ImGui::BeginChild("##Merge Options 1", size)) { - document.animation.selection = std::set(window.order.begin(), window.order.end()); - window.selection = groupIds; + ImGui::RadioButton(localize.get(LABEL_APPEND_FRAMES), &settings.mergeType, merge::APPEND); + ImGui::RadioButton(localize.get(LABEL_PREPEND_FRAMES), &settings.mergeType, merge::PREPEND); } - - auto isRowsDone = false; - animation_entries_each( - model, - [&](int index, const model::Animation* animation, const model::AnimationGroup* group) - { - if (isRowsDone) return; - if (group) - animation_group_draw(window, manager, resources, document, *group, index, arrowSelectionId, isRowsDone); - else if (animation) - isRowsDone = window_row_draw(window, manager, resources, document, index, index, arrowSelectionId); - }); - window_selection_finish(window, manager, settings, clipboard, document, arrowSelectionId); - animations_selection_set(window, document, - {document.animation.selection.begin(), document.animation.selection.end()}, - std::set(window.selection)); - }; - window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto& selection = document.animation.selection; - auto& model = document.model; - auto groupIds = edit::animation_group_ids_get(model); - auto targetGroupId = - window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) ? *window.selection.begin() : -1; - auto count = model.animations_count_get(); - auto groupIndices = - targetGroupId != -1 ? edit::animation_group_indices_get(model, targetGroupId) : std::set{}; - auto index = !selection.empty() ? std::min(*selection.rbegin() + 1, count) - : !groupIndices.empty() ? std::min(*groupIndices.rbegin() + 1, count) - : count; - auto groupId = selection.empty() ? targetGroupId : model.animation_group_id_get(*selection.rbegin()); - - document.edit_apply(EDIT_ADD_ANIMATION, - [&](model::Model& anm2) - { - auto uids = - edit::animation_add(anm2, index, groupId, document.reference_get().animationIndex, - localize.get(TEXT_NEW_ANIMATION)); - animations_selection_set(window, document, {index}, {}); - document.reference_set({index}); - window.newElementId = index; - window.scrollQueued = index; - return uids; - }); - }; - 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; - animations_erase(window, document, selection, groupSelection, - groupSelection.empty() ? EDIT_REMOVE_ANIMATIONS : EDIT_REMOVE_GROUP); - }; - 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; - animations_erase(window, document, selectedIndices, groupSelection, EDIT_CUT_ANIMATIONS); - }; - 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 text = animation_clipboard_text_get(document, window); - if (text.empty()) return; - auto selectedIndices = animation_selected_indices_get(document, window); - auto count = document.model.animations_count_get(); - 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) - { - if (clipboard.is_empty()) return; - auto& selection = document.animation.selection; - auto count = document.model.animations_count_get(); - auto groupIds = edit::animation_group_ids_get(document.model); - auto targetGroupId = - selection.empty() && window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) - ? *window.selection.begin() - : -1; - auto groupIndices = - targetGroupId != -1 ? edit::animation_group_indices_get(document.model, 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) + ImGui::EndChild(); + ImGui::SameLine(); + if (ImGui::BeginChild("##Merge Options 2", size)) { - window.scrollQueued = merged; - window.selection.clear(); + 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 = + popup_buttons_draw(manager, localize.get(LABEL_MERGE), + !animation_merge_indices_get(document, mergeSelection, mergeReference).empty(), LABEL_CLOSE); + if (result == PopupButton::CONFIRM) + command_push(panel, + [options = AnimationMergeOptions{.selection = mergeSelection, + .reference = mergeReference, + .type = (merge::Type)settings.mergeType, + .isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter}]( + Document& document) { animations_merge(document, options); }); + if (result != PopupButton::NONE) + { 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); - if (targetIndices.empty()) return; + popup.close(); + } + ImGui::EndPopup(); + popup.end(); + } - std::set targetSet(targetIndices.begin(), targetIndices.end()); - auto groupIds = edit::animation_group_ids_get(document.model); - auto groupId = groupIds.empty() ? 0 : *groupIds.rbegin() + 1; - document.edit_apply(EDIT_GROUP_ITEMS, - [&](model::Model& anm2) - { - auto uids = edit::animations_group(anm2, targetSet, localize.get(TEXT_NEW_GROUP)); - animations_selection_set(window, document, targetSet, {groupId}); - document.reference_set({*targetSet.begin()}); - window.scrollQueued = *targetSet.begin(); - return uids; - }); - }; - window.default_set = [](Window&, Manager&, Settings&, Document& document, Clipboard&) - { - auto animation = document.model.animation_get(*document.animation.selection.begin()); - if (!animation) return; - auto name = animation->name; - document.edit_apply(EDIT_DEFAULT_ANIMATION, - [&](model::Model& model) { model.animations.defaultAnimation = name; }); - }; - window.body_update = - [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard&, Document& document) - { - auto& mergeSelection = document.merge.selection; - auto mergeReference = document.merge.reference; + void animations_update(Panel& panel, AnimationsPanel& animations) + { + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& model = document.model; - window.popup.trigger(); - if (!ImGui::BeginPopupModal(window.popup.label(), &window.popup.isOpen, ImGuiWindowFlags_NoResize)) return; - - struct AnimationMergeCandidate + if (ImGui::Begin(localize.get(LABEL_ANIMATIONS_WINDOW), &settings.windowIsAnimations)) + { + auto selection = document.animations_selected_get(); + auto groupSelection = animation_groups_selected_get(document); + auto groupIds = edit::animation_group_ids_get(model); + auto count = model.animations_count_get(); + auto isItemSelected = [&]() { return !selection.empty() || !groupSelection.empty(); }; + // A single selected group is where adds and pastes go. + auto targetGroupId = [&]() { - int key{}; - std::string label{}; + return groupSelection.size() == 1 && groupIds.contains(*groupSelection.begin()) ? *groupSelection.begin() : -1; }; - std::vector candidates{}; - auto candidate_animation_push = [&](const model::Animation& animation, int animationIndex, bool isGrouped) + auto group_end_get = [&](int groupId) { - if (animationIndex != mergeReference) - candidates.push_back({animationIndex, isGrouped ? std::format(" {}", animation.name) : animation.name}); + auto indices = groupId != -1 ? edit::animation_group_indices_get(model, groupId) : std::set{}; + return indices.empty() ? count : std::min(*indices.rbegin() + 1, count); }; - animation_entries_each(document.model, - [&](int index, const model::Animation* animation, const model::AnimationGroup* group) - { - if (animation) return candidate_animation_push(*animation, index, false); - auto isReferenceOnly = group->animations.size() == 1 && index == mergeReference; - if (group->animations.empty() || isReferenceOnly) return; - candidates.push_back( - {window_group_key_get(group->id), - group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name}); - for (int i = 0; i < (int)group->animations.size(); ++i) - candidate_animation_push(*group->animations[i], index + i, true); - }); + Actions actions{}; + actions.add( + ACTION_RENAME, [&]() { return selection.size() == 1 || (selection.empty() && groupSelection.size() == 1); }, + [&]() { state.newId = selection.size() == 1 ? *selection.begin() : group_key_get(*groupSelection.begin()); }); + actions.add( + ACTION_ADD, {}, + [&]() + { + auto index = !selection.empty() ? std::min(*selection.rbegin() + 1, count) : group_end_get(targetGroupId()); + auto groupId = selection.empty() ? targetGroupId() : model.animation_group_id_get(*selection.rbegin()); + command_push(panel, + [&state, index, groupId](Document& document) + { + document.edit_apply(EDIT_ADD_ANIMATION, + [&](model::Model& model) + { + auto uids = edit::animation_add( + model, index, groupId, document.reference_get().animationIndex, + localize.get(TEXT_NEW_ANIMATION)); + animations_selection_set(document, {index}, {}); + document.reference_set({index}); + state.newId = index; + return uids; + }); + }); + }, + TOOLTIP_ADD_ANIMATION); + actions.add( + ACTION_DUPLICATE, isItemSelected, + [&]() + { + auto indices = animation_selected_indices_get(document); + auto start = indices.empty() ? count : std::min(*indices.rbegin() + 1, count); + command_push(panel, + [&state, start](Document& document) + { + auto text = animation_clipboard_text_get(document); + if (!text.empty()) + animations_insert(state, document, text, start, -1, EDIT_DUPLICATE_ANIMATIONS); + }); + }, + TOOLTIP_DUPLICATE_ANIMATION); + actions.add( + ACTION_MERGE, [&]() { return !animation_selected_indices_get(document).empty(); }, + [&]() + { + command_push(panel, + [&state](Document& document) + { + auto merged = animations_merge(document, {}); + if (merged != -1) state.scrollId = merged; + }); + }, + TOOLTIP_OPEN_MERGE_POPUP); + actions.add( + ACTION_GROUP, [&]() { return !animation_groupable_indices_get(document).empty(); }, + [&]() + { + auto targets = animation_groupable_indices_get(document); + command_push(panel, + [&state, targets = std::set(targets.begin(), targets.end())](Document& document) + { + auto groupIds = edit::animation_group_ids_get(document.model); + auto groupId = groupIds.empty() ? 0 : *groupIds.rbegin() + 1; + document.edit_apply(EDIT_GROUP_ITEMS, + [&](model::Model& model) + { + auto uids = edit::animations_group(model, targets, + localize.get(TEXT_NEW_GROUP)); + animations_selection_set(document, targets, {groupId}); + document.reference_set({*targets.begin()}); + state.scrollId = *targets.begin(); + return uids; + }); + }); + }); + actions.add( + ACTION_REMOVE, isItemSelected, + [&]() + { + command_push(panel, + [selection, groupSelection](Document& document) + { + animations_erase(document, selection, groupSelection, + groupSelection.empty() ? EDIT_REMOVE_ANIMATIONS : EDIT_REMOVE_GROUP); + }); + }, + TOOLTIP_REMOVE_ANIMATION); + actions.add( + ACTION_DEFAULT, [&]() { return selection.size() == 1; }, + [&]() + { + command_push(panel, + [index = *selection.begin()](Document& document) + { + auto animation = document.model.animation_get(index); + if (!animation) return; + document.edit_apply(EDIT_DEFAULT_ANIMATION, [name = animation->name](model::Model& model) + { model.animations.defaultAnimation = name; }); + }); + }, + TOOLTIP_SET_DEFAULT_ANIMATION); + actions.separator(); + actions.add(ACTION_CUT, isItemSelected, + [&]() + { + clipboard.set(animation_clipboard_text_get(document)); + command_push( + panel, [indices = animation_selected_indices_get(document), groupSelection](Document& document) + { animations_erase(document, indices, groupSelection, EDIT_CUT_ANIMATIONS); }); + }); + actions.add(ACTION_COPY, isItemSelected, [&]() { clipboard.set(animation_clipboard_text_get(document)); }); + actions.add( + ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, + [&]() + { + auto groupId = selection.empty() ? targetGroupId() : -1; + auto start = !selection.empty() ? *selection.rbegin() + 1 : group_end_get(groupId); + command_push(panel, [&state, text = clipboard.get(), start, groupId](Document& document) + { animations_insert(state, document, text, start, groupId, EDIT_PASTE_ANIMATIONS); }); + }); - 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) + // The footer's merge opens the merge popup (merging into the first selected animation). + auto footerActions = actions; + if (groupSelection.empty()) + std::ranges::find(footerActions.items, ACTION_MERGE, &Action::type)->run = [&]() { - 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 (selection.empty()) return; + animations.mergeSelection.clear(); + animations.mergeReference = *selection.begin(); + animations.mergePopup.open(); + }; - 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(); + ListRows rows{.label_get = [&](int index) { return model.animation_get(index)->name; }, + .name_get = [&](int index) { return model.animation_get(index)->name; }, + .rename = + [&](int index, const std::string& name) + { + command_push(panel, + [index, name](Document& document) + { + document.edit_apply(SNAPSHOT_RENAME_ANIMATION, + [&](model::Model& model) + { + auto animation = model.animation_edit(index); + if (!animation) return; + if (model.animations_count_get() == 1) + model.animations.defaultAnimation = name; + animation->name = name; + }); + }); + }, + .font_get = + [&](int index) + { + auto animation = model.animation_get(index); + auto isDefault = animation && model.animations.defaultAnimation == animation->name; + auto isFocused = document.reference_get().animationIndex == index; + return isDefault && isFocused ? font::BOLD_ITALICS + : isDefault ? font::BOLD + : isFocused ? font::ITALICS + : font::REGULAR; + }, + .tooltip_draw = + [&](int index) + { + auto& animation = *model.animation_get(index); + tooltip_name_draw(resources, animation.name); + if (model.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()); + }, + .select = + [&](int index) + { + auto& io = ImGui::GetIO(); + if (!io.KeyCtrl && !io.KeyShift) groupSelection.clear(); + document.reference_set({index}); + document.frame_references_clear(); + }, + .drag_drop_update = [&](int index, int) { return animation_row_drag_drop_update(panel, index); }}; - if (ImGui::BeginChild("##Merge Delete After", deleteAfterSize, ImGuiChildFlags_Borders)) - ImGui::Checkbox(localize.get(LABEL_DELETE_ANIMATIONS_AFTER), &settings.mergeIsDeleteAnimationsAfter); - ImGui::EndChild(); + list_panel_draw( + panel, actions, {{ACTION_ADD, ACTION_DUPLICATE, ACTION_MERGE, ACTION_REMOVE, ACTION_DEFAULT}}, + [&]() + { + std::vector visibleKeys{}; + state.keys.clear(); + for (int i = 0; i < count; ++i) + state.keys.push_back(i); + animation_entries_each(model, + [&](int index, const model::Animation* animation, const model::AnimationGroup* group) + { + if (animation) visibleKeys.push_back(index); + if (group && group->isExpanded) + for (int i = 0; i < (int)group->animations.size(); ++i) + visibleKeys.push_back(index + i); + }); - 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 count = document.model.animations_count_get(); - if ((!isPrevious && !isNext) || count <= 0) return; + auto focus = document.reference_get().animationIndex; + auto arrowKey = list_select_begin(panel, selection, focus, rows, visibleKeys); + auto isRowsDone = false; + animation_entries_each(model, + [&](int index, const model::Animation* animation, const model::AnimationGroup* group) + { + if (isRowsDone) return; + if (group) + isRowsDone = animation_group_draw(panel, selection, groupSelection, focus, rows, + *group, index, arrowKey); + else if (animation) + isRowsDone = row_draw(panel, selection, focus, rows, index, index, arrowKey); + }); + list_select_end(panel, selection, focus, rows, arrowKey); + animations_selection_set(document, selection, groupSelection); + }, + &footerActions); + } + ImGui::End(); - auto reference = document.reference_get(); - reference.animationIndex = std::clamp(reference.animationIndex + (isNext ? 1 : -1), 0, count - 1); - document.reference_set(reference); - animations_selection_set(window, document, {reference.animationIndex}, std::set(window.selection)); - window.scrollQueued = reference.animationIndex; - }; - return window; + animations_merge_popup_update(panel, animations); + + auto isNext = shortcut(manager.chords[SHORTCUT_NEXT_ANIMATION], shortcut::GLOBAL); + auto isPrevious = shortcut(manager.chords[SHORTCUT_PREVIOUS_ANIMATION], shortcut::GLOBAL); + auto count = model.animations_count_get(); + if ((!isPrevious && !isNext) || count <= 0) return; + auto reference = document.reference_get(); + reference.animationIndex = std::clamp(reference.animationIndex + (isNext ? 1 : -1), 0, count - 1); + document.reference_set(reference); + animations_selection_set(document, {reference.animationIndex}, animation_groups_selected_get(document)); + state.scrollId = reference.animationIndex; } } diff --git a/src/imgui/window/frame_properties.cpp b/src/imgui/window/frame_properties.cpp index a2d4c41..e083414 100644 --- a/src/imgui/window/frame_properties.cpp +++ b/src/imgui/window/frame_properties.cpp @@ -79,10 +79,10 @@ namespace anm2ed::imgui }}); }; - auto regions = document.layer_regions_get(type == LAYER ? reference.itemID : -1); - auto noneLabel = std::string(localize.get(BASIC_NONE)); - auto regionLabels = regions ? regions->labels : std::vector{noneLabel.c_str()}; - auto regionIds = regions ? regions->ids : std::vector{-1}; + auto regions = document.choices_get(SelectionKind::REGIONS, type == LAYER ? reference.itemID : -1); + auto events = document.choices_get(SelectionKind::EVENTS); + auto sounds = document.choices_get(SelectionKind::SOUNDS); + auto shaders = document.choices_get(SelectionKind::SHADERS); std::vector interpolationLabels{}; for (auto label : INTERPOLATION_LABELS) interpolationLabels.push_back(localize.get(label)); @@ -115,7 +115,7 @@ namespace anm2ed::imgui if (type == TRIGGER) { if (combo_id_mapped(localize.get(BASIC_EVENT), frame ? &useFrame.eventId : &dummy_value_negative(), - document.event.ids, document.event.labels) && + events.ids, events.labels) && frame) { auto eventId = useFrame.eventId; @@ -166,8 +166,8 @@ namespace anm2ed::imgui for (auto [i, id] : std::views::enumerate(useFrame.soundIds)) { ImGui::PushID(i); - if (combo_id_mapped("##Sound", frame ? &id : &dummy_value_negative(), document.sound.ids, - document.sound.labels) && + if (combo_id_mapped("##Sound", frame ? &id : &dummy_value_negative(), sounds.ids, + sounds.labels) && frame) { auto soundIndex = (std::size_t)i; @@ -260,7 +260,7 @@ namespace anm2ed::imgui ImGui::BeginDisabled(type != LAYER); if (combo_id_mapped(localize.get(BASIC_REGION), frame ? &useFrame.regionId : &dummy_value_negative(), - regionIds, regionLabels) && + regions.ids, regions.labels) && frame) { auto regionId = useFrame.regionId; @@ -288,7 +288,7 @@ namespace anm2ed::imgui ImGui::BeginDisabled(type != LAYER); if (combo_id_mapped(localize.get(BASIC_SHADER), frame ? &useFrame.shaderId : &dummy_value_negative(), - document.shader.ids, document.shader.labels) && + shaders.ids, shaders.labels) && frame) { auto shaderId = useFrame.shaderId; diff --git a/src/imgui/window/items.cpp b/src/imgui/window/items.cpp index 79ff1db..fe29ac4 100644 --- a/src/imgui/window/items.cpp +++ b/src/imgui/window/items.cpp @@ -1,4 +1,4 @@ -#include "window.hpp" +#include "panel.hpp" #include @@ -11,28 +11,25 @@ namespace anm2ed::imgui { constexpr int ITEM_PROPERTIES_ROWS = 2; - std::vector* layers_get(Document&, model::Model& model) { return &model.content.layers; } - std::vector* nulls_get(Document&, model::Model& model) { return &model.content.nulls; } + auto& layers_get(model::Model& model) { return model.content.layers; } + auto& nulls_get(model::Model& model) { return model.content.nulls; } + auto& events_get(model::Model& model) { return model.content.events; } void item_tooltip_draw(Resources& resources, const std::string& name, int id) { - window_tooltip_name_draw(resources, name); + tooltip_name_draw(resources, name); ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); } - void item_tooltip_set(Window& window) + // The layer/null properties popup: adds a new item (id -1) or replaces the edited one, then selects it. + template + void item_properties_update(Panel& panel, int popupIndex, SelectionKind kind, StringType nameTooltip, + StringType addEdit, StringType propertiesEdit, ItemsGet items_get, + FieldsDraw&& fields_draw) { - window.tooltip_draw = [name_get = window.name_get](Document& document, Resources& resources, int id) - { item_tooltip_draw(resources, name_get(document, id), id); }; - } - - template - void item_properties_popup_update(Window& window, Manager& manager, Document& document, StringType nameTooltip, - std::function*(Document&, model::Model&)> items_get, - const std::function& fields_draw) - { - auto& popup = manager.itemPropertiesPopups[window.elementType == ElementType::LAYER_ELEMENT ? 0 : 1]; - auto reference = window.storage_get(document).reference; + auto& manager = panel.manager; + auto& popup = manager.itemPropertiesPopups[popupIndex]; + auto& edit = manager.itemEdit; popup.trigger(); if (ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) @@ -40,19 +37,44 @@ namespace anm2ed::imgui 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); + input_text_string(localize.get(BASIC_NAME), &edit.name); ImGui::SetItemTooltip("%s", localize.get(nameTooltip)); - fields_draw(manager.itemEdit); + fields_draw(edit); } ImGui::EndChild(); - auto result = window_popup_buttons_draw(manager, localize.get(reference == -1 ? BASIC_ADD : BASIC_CONFIRM)); + auto result = popup_buttons_draw(manager, localize.get(edit.id == -1 ? BASIC_ADD : BASIC_CONFIRM)); if (result == PopupButton::CONFIRM) { - Item item{.name = manager.itemEdit.name}; - if constexpr (requires { item.spritesheetId; }) item.spritesheetId = manager.itemEdit.spritesheetId; - if constexpr (requires { item.isShowRect; }) item.isShowRect = manager.itemEdit.isShowRect; - window_item_apply_push(window, manager, item, reference, items_get); + Item item{.name = edit.name}; + if constexpr (requires { item.spritesheetId; }) item.spritesheetId = edit.spritesheetId; + if constexpr (requires { item.isShowRect; }) item.isShowRect = edit.isShowRect; + auto& state = panel.state; + command_push(panel, + [&state, item, id = edit.id, kind, addEdit, propertiesEdit, items_get](Document& document) + { + auto changedId = id; + document.edit_apply(id == -1 ? addEdit : propertiesEdit, + [&](model::Model& model) + { + auto& items = items_get(model); + if (auto target = model::item_get(items, id)) + { + auto uid = target->uid; + *target = item; + target->uid = uid; + target->id = id; + return; + } + if (id != -1) return; + changedId = model::item_next_id_get(items); + items.push_back(item); + items.back().id = changedId; + state.newId = changedId; + }); + document.selected_ids_set(kind, {changedId}); + document.focused_id_set(kind, changedId); + }); } if (result != PopupButton::NONE) popup.close(); ImGui::EndPopup(); @@ -60,118 +82,159 @@ namespace anm2ed::imgui popup.end(); } - Window item_window_make(StringType title, bool Settings::* isOpen, ElementType elementType, const char* childLabel, - StringType addTooltip, StringType removeUnusedTooltip) + // Layers and nulls: properties popup, add, remove unused, copy and paste. + template + void track_items_actions_add(Actions& actions, Panel& panel, SelectionKind kind, ElementType type, + StringType addTooltip, StringType removeUnusedTooltip, StringType removeUnusedEdit, + StringType pasteEdit, StringType pasteFailToast, ItemsGet items_get) { - Window window{}; - window.title = title; - window.isOpen = isOpen; - 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.properties_open = [elementType](Manager& manager, int id) { manager.item_properties_open(elementType, id); }; - return window; + auto selection = panel.document.selected_ids_get(kind); + auto& manager = panel.manager; + actions.add( + ACTION_PROPERTIES, [selection]() { return selection.size() == 1; }, + [&manager, type, selection]() { manager.item_properties_open(type, *selection.begin()); }); + actions.add(ACTION_ADD, {}, [&manager, type]() { manager.item_properties_open(type, -1); }, addTooltip); + actions.add( + ACTION_REMOVE_UNUSED, {}, [&panel, type, removeUnusedEdit, items_get]() + { items_unused_remove(panel, type, removeUnusedEdit, items_get); }, removeUnusedTooltip); + items_clipboard_actions_add(actions, panel, kind, pasteEdit, pasteFailToast, items_get); } - Window layers_window_register() + void layers_update(Panel& panel) { - auto window = item_window_make(LABEL_LAYERS_WINDOW, &Settings::windowIsLayers, 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_items_bind(window, layers_get); - window.row_label_get = [](Document& document, int id) + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& layers = document.model.content.layers; + if (ImGui::Begin(localize.get(LABEL_LAYERS_WINDOW), &settings.windowIsLayers)) { - auto layer = model::item_get(document.model.content.layers, id); - return std::vformat(localize.get(FORMAT_LAYER), - std::make_format_args(layer->id, layer->name, layer->spritesheetId)); - }; - window.tooltip_draw = [](Document& document, Resources& resources, int id) - { - auto layer = model::item_get(document.model.content.layers, id); - item_tooltip_draw(resources, layer->name, id); - 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, layers_get, - [&](Manager::ItemEdit& 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; + Actions actions{}; + track_items_actions_add(actions, panel, SelectionKind::LAYERS, ElementType::LAYER_ELEMENT, + TOOLTIP_ADD_LAYER, TOOLTIP_REMOVE_UNUSED_LAYERS, EDIT_REMOVE_UNUSED_LAYERS, + EDIT_PASTE_LAYERS, TOAST_DESERIALIZE_LAYERS_FAILED, layers_get); + ListRows rows{ + .label_get = + [&](int id) + { + auto layer = model::item_get(layers, id); + return std::vformat(localize.get(FORMAT_LAYER), + std::make_format_args(layer->id, layer->name, layer->spritesheetId)); + }, + .tooltip_draw = + [&](int id) + { + auto layer = model::item_get(layers, id); + item_tooltip_draw(resources, layer->name, id); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_SPRITESHEET_ID), std::make_format_args(layer->spritesheetId)).c_str()); + }, + .activate = [&](int id) { manager.item_properties_open(ElementType::LAYER_ELEMENT, id); }}; + list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED}}, + [&]() { content_list_draw(panel, SelectionKind::LAYERS, item_ids_get(layers), rows); }); + } + ImGui::End(); + + item_properties_update( + panel, 0, SelectionKind::LAYERS, TOOLTIP_ITEM_NAME, EDIT_ADD_LAYER, EDIT_SET_LAYER_PROPERTIES, layers_get, + [&](Manager::ItemEdit& layer) + { + auto spritesheets = document.choices_get(SelectionKind::SPRITESHEETS); + combo_id_mapped(localize.get(LABEL_SPRITESHEET), &layer.spritesheetId, spritesheets.ids, spritesheets.labels); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SPRITESHEET)); + }); } - Window nulls_window_register() + void nulls_update(Panel& panel) { - auto window = item_window_make(LABEL_NULLS_WINDOW, &Settings::windowIsNulls, 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_items_bind(window, nulls_get); - item_tooltip_set(window); - window.row_label_get = [name_get = window.name_get](Document& document, int id) + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& nulls = document.model.content.nulls; + if (ImGui::Begin(localize.get(LABEL_NULLS_WINDOW), &settings.windowIsNulls)) { - auto name = name_get(document, id); - return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, name)); - }; - window.popup_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) - { - item_properties_popup_update(window, manager, document, TOOLTIP_NULL_NAME, nulls_get, - [](Manager::ItemEdit& null) - { - ImGui::Checkbox(localize.get(LABEL_RECT), &null.isShowRect); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_RECT)); - }); - }; - return window; + Actions actions{}; + track_items_actions_add(actions, panel, SelectionKind::NULLS, ElementType::NULL_ELEMENT, + TOOLTIP_ADD_NULL, TOOLTIP_REMOVE_UNUSED_NULLS, EDIT_REMOVE_UNUSED_NULLS, + EDIT_PASTE_NULLS, TOAST_DESERIALIZE_NULLS_FAILED, nulls_get); + ListRows rows{.label_get = + [&](int id) + { + auto name = model::item_get(nulls, id)->name; + return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, name)); + }, + .tooltip_draw = [&](int id) { item_tooltip_draw(resources, model::item_get(nulls, id)->name, id); }, + .activate = [&](int id) { manager.item_properties_open(ElementType::NULL_ELEMENT, id); }, + .isFocusItalic = true}; + list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED}}, + [&]() { content_list_draw(panel, SelectionKind::NULLS, item_ids_get(nulls), rows); }); + } + ImGui::End(); + + item_properties_update(panel, 1, SelectionKind::NULLS, TOOLTIP_NULL_NAME, EDIT_ADD_NULL, + EDIT_SET_NULL_PROPERTIES, nulls_get, + [](Manager::ItemEdit& null) + { + ImGui::Checkbox(localize.get(LABEL_RECT), &null.isShowRect); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_RECT)); + }); } - Window events_window_register() + void events_update(Panel& panel) { - auto window = item_window_make(LABEL_EVENTS_WINDOW, &Settings::windowIsEvents, 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_items_bind(window, [](Document&, model::Model& model) { return &model.content.events; }); - item_tooltip_set(window); - window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& events = document.model.content.events; + if (ImGui::Begin(localize.get(LABEL_EVENTS_WINDOW), &settings.windowIsEvents)) { - document.edit_apply(window.addEdit, - [&](model::Model& model) - { - auto& events = model.content.events; - auto& event = events.emplace_back(model::Event{.id = model::item_next_id_get(events), - .name = localize.get(TEXT_NEW_EVENT)}); - auto& storage = window.storage_get(document); - storage.selection = {event.id}; - storage.reference = event.id; - window.newElementId = event.id; - }); - }; - return window; + auto selection = document.selected_ids_get(SelectionKind::EVENTS); + Actions actions{}; + actions.add( + ACTION_RENAME, [selection]() { return selection.size() == 1; }, + [&state, selection]() { state.newId = *selection.begin(); }); + actions.add( + ACTION_ADD, {}, + [&panel]() + { + auto& state = panel.state; + command_push(panel, + [&state](Document& document) + { + int id{}; + document.edit_apply(EDIT_ADD_EVENT, + [&](model::Model& model) + { + auto& events = model.content.events; + id = model::item_next_id_get(events); + events.push_back({.id = id, .name = localize.get(TEXT_NEW_EVENT)}); + }); + document.selected_ids_set(SelectionKind::EVENTS, {id}); + document.focused_id_set(SelectionKind::EVENTS, id); + state.newId = id; + }); + }, + TOOLTIP_ADD_EVENT); + actions.add( + ACTION_REMOVE_UNUSED, {}, + [&panel]() { items_unused_remove(panel, ElementType::EVENT_ELEMENT, EDIT_REMOVE_UNUSED_EVENTS, events_get); }, + TOOLTIP_REMOVE_UNUSED_EVENTS); + items_clipboard_actions_add(actions, panel, SelectionKind::EVENTS, EDIT_PASTE_EVENTS, + TOAST_DESERIALIZE_EVENTS_FAILED, events_get); + ListRows rows{.label_get = [&](int id) { return model::item_get(events, id)->name; }, + .name_get = [&](int id) { return model::item_get(events, id)->name; }, + .rename = + [&](int id, const std::string& name) + { + command_push(panel, + [id, name](Document& document) + { + document.edit_apply(EDIT_RENAME_EVENT, + [&](model::Model& model) + { + if (auto event = model::item_get(model.content.events, id)) + event->name = name; + }); + }); + }, + .tooltip_draw = [&](int id) + { item_tooltip_draw(resources, model::item_get(events, id)->name, id); }}; + list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED}}, + [&]() { content_list_draw(panel, SelectionKind::EVENTS, item_ids_get(events), rows); }); + } + ImGui::End(); } } diff --git a/src/imgui/window/panel.cpp b/src/imgui/window/panel.cpp new file mode 100644 index 0000000..e22fca7 --- /dev/null +++ b/src/imgui/window/panel.cpp @@ -0,0 +1,353 @@ +#include "panel.hpp" + +#include +#include +#include + +#include "path.hpp" +#include "strings.hpp" +#include "util/imgui/layout.hpp" +#include "util/imgui/shortcut.hpp" + +using namespace anm2ed::resource; +using namespace anm2ed::types; +using namespace anm2ed::util; +using namespace glm; + +namespace anm2ed::imgui +{ + 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"; + + bool is_drag_drop_active() { return ImGui::GetDragDropPayload() != nullptr; } + + void command_push(const Panel& panel, std::function run) + { + panel.manager.command_push( + {panel.manager.selected, [run = std::move(run)](Manager&, Document& document) { run(document); }}); + } + + void row_select(std::set&, int& focus, const ListRows& rows, int key) + { + focus = key; + if (rows.select) rows.select(key); + } + + void row_scroll_update(PanelState& state, int key, int arrowKey) + { + if ((state.newId != key && state.scrollId != key && arrowKey != key) || is_drag_drop_active()) return; + ImGui::SetScrollHereY(SCROLL_CENTER); + if (state.scrollId == key) state.scrollId = -1; + } + + void row_tooltip_update(const ListRows& rows, int key) + { + if (!rows.tooltip_draw) return; + if (ImGui::BeginItemTooltip()) + { + rows.tooltip_draw(key); + ImGui::EndTooltip(); + } + } + + // Arrow keys move a single selection through the keys. + int arrow_key_get(const std::vector& keys, const std::set& selection, int focus) + { + if (keys.empty() || !ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) || + !(ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) + return -1; + auto current = focus == -1 && !selection.empty() ? *selection.begin() : focus; + auto it = std::ranges::find(keys, current); + auto index = it == keys.end() ? 0 : (int)std::distance(keys.begin(), it); + auto delta = ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) ? -1 : 1; + return keys[std::clamp(index + delta, 0, (int)keys.size() - 1)]; + } + + // Multi-select over `keys` (row index -> key); returns the key the arrow keys moved to, or -1. + int list_select_begin(Panel& panel, std::set& selection, int& focus, const ListRows& rows, + const std::vector& arrowKeys) + { + auto& storage = panel.state.selection; + storage = selection; + storage.set_index_map(&panel.state.keys); + storage.start(panel.state.keys.size()); + selection = storage; + if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + selection = storage = std::set(panel.state.keys.begin(), panel.state.keys.end()); + if (ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) + { + storage.clear(); + selection.clear(); + row_select(selection, focus, rows, -1); + } + return arrow_key_get(arrowKeys, selection, focus); + } + + void list_select_end(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int arrowKey) + { + auto& storage = panel.state.selection; + storage.finish(); + storage.set_index_map(nullptr); + selection = storage; + if (arrowKey != -1) + { + selection = {arrowKey}; + row_select(selection, focus, rows, arrowKey); + } + if (shortcut(panel.manager.chords[SHORTCUT_CONFIRM], shortcut::FOCUSED) && selection.size() == 1 && rows.activate) + rows.activate(*selection.begin()); + } + + bool row_draw(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int key, int index, + int arrowKey) + { + auto& state = panel.state; + auto isSelected = selection.contains(key) || arrowKey == key; + auto isFocused = rows.isFocusItalic && (focus == key || arrowKey == key); + auto font = rows.font_get ? rows.font_get(key) : isFocused ? font::ITALICS : font::REGULAR; + auto label = rows.label_get(key); + + ImGui::PushID(key); + ImGui::SetNextItemSelectionUserData(index); + if (font != font::REGULAR) ImGui::PushFont(panel.resources.fonts[font].get(), font::SIZE); + if (arrowKey == key) ImGui::SetKeyboardFocusHere(); + + bool isActivated{}; + if (rows.rename) + { + if (state.newId == key) + { + state.renameState = RENAME_FORCE_EDIT; + state.newId = -1; + } + auto isRenaming = state.renameId == key; + auto name = rows.name_get(key); + auto renameLabel = std::format("###Document #{} Row #{}", panel.manager.selected, key); + isActivated = selectable_input_text(label, renameLabel, isRenaming ? state.renameText : name, isSelected, + ImGuiSelectableFlags_None, state.renameState); + if (isActivated && state.renameState == RENAME_BEGIN) + { + state.renameId = key; + state.renameText = name; + } + else if (isActivated && state.renameState == RENAME_FINISHED) + { + if (isRenaming && state.renameText != name) rows.rename(key, state.renameText); + state.renameId = -1; + state.renameText.clear(); + } + } + else + isActivated = ImGui::Selectable(label.c_str(), isSelected); + + if (isActivated || ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right)) + row_select(selection, focus, rows, key); + if (font != font::REGULAR) ImGui::PopFont(); + row_scroll_update(state, key, arrowKey); + if (state.newId == key) state.newId = -1; + + if (rows.activate && ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + rows.activate(key); + + auto isBreak = rows.drag_drop_update && rows.drag_drop_update(key, index); + row_tooltip_update(rows, key); + ImGui::PopID(); + return isBreak; + } + + void card_draw(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int key, int index, + int arrowKey, bool& isBreak) + { + auto cardSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * rows.cardLines); + auto style = ImGui::GetStyle(); + + ImGui::PushID(key); + if (arrowKey == key) + { + 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(); + } + + if (ImGui::BeginChild("##Card Child", cardSize, ImGuiChildFlags_Borders)) + { + auto cursorPos = ImGui::GetCursorPos(); + auto isSelected = selection.contains(key) || arrowKey == key; + auto isFocused = key == focus || arrowKey == key; + auto image = rows.image_get(key); + auto label = rows.label_get(key); + + ImGui::SetNextItemSelectionUserData(index); + ImGui::SetNextItemStorageID(key); + if (arrowKey == key) ImGui::SetKeyboardFocusHere(); + if (ImGui::Selectable("##Card Selectable", isSelected, 0, cardSize) || + ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right)) + row_select(selection, focus, rows, key); + if (rows.activate && ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + rows.activate(key); + + if (rows.tooltip_draw && ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip) && + !ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + ImGui::SetNextWindowSize(ImVec2(ImGui::CalcTextSize(label.c_str()).x + style.ItemSpacing.x + + style.WindowPadding.x * TOOLTIP_PADDING_MULTIPLIER, + 0), + ImGuiCond_Appearing); + row_tooltip_update(rows, key); + } + + isBreak = rows.drag_drop_update && rows.drag_drop_update(key, index); + + 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(resource::texture::id_get(*image.texture), imageSize, to_imvec2(image.uvMin), + to_imvec2(image.uvMax), ImVec4(), image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID); + + ImGui::SetCursorPos( + ImVec2(cardSize.y + style.ItemSpacing.x, cardSize.y - cardSize.y / 2 - ImGui::GetTextLineHeight() / 2)); + if (isFocused) ImGui::PushFont(panel.resources.fonts[font::ITALICS].get(), font::SIZE); + ImGui::TextUnformatted(label.c_str()); + if (isFocused) ImGui::PopFont(); + } + ImGui::EndChild(); + + row_scroll_update(panel.state, key, -1); + if (panel.state.newId == key) panel.state.newId = -1; + ImGui::PopID(); + } + + // A selectable list (or cards) of keys; `selection` and `focus` are read and written. + void list_draw(Panel& panel, const std::vector& keys, std::set& selection, int& focus, const ListRows& rows) + { + panel.state.keys = keys; + auto isCards = rows.image_get != nullptr; + if (isCards) ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + auto arrowKey = list_select_begin(panel, selection, focus, rows, keys); + for (int i = 0; i < (int)keys.size(); ++i) + { + bool isBreak{}; + if (isCards) + card_draw(panel, selection, focus, rows, keys[i], i, arrowKey, isBreak); + else + isBreak = row_draw(panel, selection, focus, rows, keys[i], i, arrowKey); + if (isBreak) break; + } + if (isCards) ImGui::PopStyleVar(); + list_select_end(panel, selection, focus, rows, arrowKey); + } + + void content_list_draw(Panel& panel, SelectionKind kind, const std::vector& keys, const ListRows& rows) + { + auto& document = panel.document; + auto selection = document.selected_ids_get(kind); + auto focus = document.focused_id_get(kind); + list_draw(panel, keys, selection, focus, rows); + document.selected_ids_set(kind, selection); + document.focused_id_set(kind, focus); + } + + // The list in a bordered child with its context menu and shortcuts, then the footer buttons. + void list_panel_draw(Panel& panel, Actions& actions, const Footer& footer, const std::function& list, + Actions* footerActions) + { + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + if (ImGui::BeginChild("##List Child", size_without_footer_get((int)footer.size()), ImGuiChildFlags_Borders)) + { + list(); + actions_shortcuts_update(actions, manager); + } + ImGui::EndChild(); + + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && + ImGui::IsMouseReleased(ImGuiMouseButton_Right)) + ImGui::OpenPopup(CONTEXT_MENU_LABEL); + Actions menu{}; + actions_undo_redo_add(menu, manager, document); + menu.separator(); + menu.items.insert(menu.items.end(), actions.items.begin(), actions.items.end()); + actions_popup_draw(CONTEXT_MENU_LABEL, menu, settings); + + auto& buttons = footerActions ? *footerActions : actions; + for (const auto& row : footer) + { + auto widgetSize = widget_size_with_row_get((int)row.size()); + bool isSameLine{}; + for (auto type : row) + if (auto action = std::ranges::find(buttons.items, type, &Action::type); action != buttons.items.end()) + action_button_draw(*action, manager, settings, widgetSize, isSameLine); + } + } + + void 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 tooltip_image_draw(const CardImage& 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(resource::texture::id_get(*image.texture), 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(); + } + + std::filesystem::path asset_path_get(Document& document, const std::filesystem::path& path) + { + return path::backslash_replace(path::make_relative(path::backslash_handle(path), document.directory_get())); + } + + void directory_open(Dialog& dialog, Document& document, const std::filesystem::path& path) + { + if (path.empty()) return; + std::error_code ec{}; + auto absolutePath = std::filesystem::weakly_canonical(document.directory_get() / path, ec); + if (ec) absolutePath = document.directory_get() / path; + auto target = std::filesystem::is_directory(absolutePath) ? absolutePath + : std::filesystem::is_directory(absolutePath.parent_path()) ? absolutePath.parent_path() + : document.directory_get(); + dialog.file_explorer_open(target); + } + + PopupButton popup_buttons_draw(Manager& manager, const char* confirmLabel, bool isConfirmEnabled, + StringType cancelLabel) + { + auto widgetSize = widget_size_with_row_get(2); + auto result = PopupButton::NONE; + + ImGui::BeginDisabled(!isConfirmEnabled); + shortcut(manager.chords[SHORTCUT_CONFIRM]); + if (ImGui::Button(confirmLabel, widgetSize)) result = PopupButton::CONFIRM; + ImGui::EndDisabled(); + + ImGui::SameLine(); + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(cancelLabel), widgetSize)) result = PopupButton::CANCEL; + return result; + } +} diff --git a/src/imgui/window/panel.hpp b/src/imgui/window/panel.hpp new file mode 100644 index 0000000..82ca660 --- /dev/null +++ b/src/imgui/window/panel.hpp @@ -0,0 +1,215 @@ +#pragma once + +#include +#include +#include +#include + +#include "actions.hpp" +#include "clipboard.hpp" +#include "dialog.hpp" +#include "manager.hpp" +#include "model/xml.hpp" +#include "resources.hpp" +#include "settings.hpp" +#include "toast.hpp" +#include "util/imgui/multiselect.hpp" +#include "util/imgui/popup.hpp" +#include "util/imgui/selectable.hpp" + +// Panels are plain functions: each draws from the document and its selection, and queues edits as commands. +namespace anm2ed::imgui +{ + 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); + + using Footer = std::vector>; + + struct CardImage + { + const resource::Image* texture{}; + glm::vec2 size{}; + glm::vec2 uvMin{}; + glm::vec2 uvMax{1.0f}; + bool isValid{}; + }; + + // What a list panel remembers between frames. + struct PanelState + { + int newId{-1}; + int scrollId{-1}; + int renameId{-1}; + std::string renameText{}; + RenameState renameState{RENAME_SELECTABLE}; + std::vector keys{}; + std::vector dragIds{}; + MultiSelectStorage selection{}; + }; + + // Everything a panel draws with, for one frame. Commands get the document again when they run. + struct Panel + { + Manager& manager; + Settings& settings; + Resources& resources; + Dialog& dialog; + Clipboard& clipboard; + Document& document; + PanelState& state; + }; + + // How a list shows its keys; only `label_get` is required. With `image_get` the rows are cards. + struct ListRows + { + std::function label_get{}; + std::function name_get{}; + std::function rename{}; + std::function font_get{}; + std::function tooltip_draw{}; + std::function image_get{}; + std::function select{}; + std::function activate{}; + std::function drag_drop_update{}; + int cardLines{}; + bool isFocusItalic{}; + }; + + enum class PopupButton + { + NONE, + CONFIRM, + CANCEL + }; + + bool is_drag_drop_active(); + void command_push(const Panel&, std::function); + bool row_draw(Panel&, std::set&, int&, const ListRows&, int, int, int); + void list_draw(Panel&, const std::vector&, std::set&, int&, const ListRows&); + void content_list_draw(Panel&, SelectionKind, const std::vector&, const ListRows&); + int list_select_begin(Panel&, std::set&, int&, const ListRows&, const std::vector&); + void list_select_end(Panel&, std::set&, int&, const ListRows&, int); + void list_panel_draw(Panel&, Actions&, const Footer&, const std::function&, Actions* = nullptr); + void tooltip_name_draw(Resources&, const std::string&); + void tooltip_image_draw(const CardImage&, const std::function&); + void directory_open(Dialog&, Document&, const std::filesystem::path&); + std::filesystem::path asset_path_get(Document&, const std::filesystem::path&); + PopupButton popup_buttons_draw(Manager&, const char*, bool = true, StringType = BASIC_CANCEL); + + struct SpritesheetsPanel + { + PanelState state{}; + PopupHelper mergePopup{PopupHelper(LABEL_SPRITESHEETS_MERGE_POPUP, POPUP_SMALL_NO_HEIGHT)}; + PopupHelper packPopup{PopupHelper(LABEL_SPRITESHEETS_PACK_POPUP, POPUP_SMALL_NO_HEIGHT)}; + PopupHelper overwritePopup{PopupHelper(LABEL_TASKBAR_OVERWRITE_FILE, POPUP_SMALL_NO_HEIGHT)}; + std::set mergeIds{}; + std::set saveIds{}; + int packId{-1}; + }; + + struct RegionsPanel + { + PanelState state{}; + PopupHelper propertiesPopup{PopupHelper(LABEL_REGION_PROPERTIES, POPUP_SMALL_NO_HEIGHT)}; + PopupHelper exportPopup{PopupHelper(LABEL_EXPORT_REGION, POPUP_SMALL_NO_HEIGHT)}; + model::Region editRegion{}; + int editId{-1}; + int exportId{-1}; + }; + + struct AnimationsPanel + { + PanelState state{}; + PopupHelper mergePopup{PopupHelper(LABEL_ANIMATIONS_MERGE_POPUP)}; + MultiSelectStorage mergeSelection{}; + std::vector mergeKeys{}; + int mergeReference{-1}; + }; + + void animations_update(Panel&, AnimationsPanel&); + void layers_update(Panel&); + void nulls_update(Panel&); + void events_update(Panel&); + void sounds_update(Panel&); + void spritesheets_update(Panel&, SpritesheetsPanel&); + void regions_update(Panel&, RegionsPanel&); + + template std::vector item_ids_get(const Items& items) + { + std::vector ids{}; + for (const auto& item : items) + ids.push_back(item.id); + return ids; + } + + template void items_copy(Clipboard& clipboard, const Items& items, const std::set& ids) + { + std::string text{}; + for (auto id : ids) + if (auto item = model::item_get(items, id)) text += model::item_to_string(*item); + if (!text.empty()) clipboard.set(text); + } + + // Pastes clipboard items into a content list with fresh ids and selects the last one. + template + void items_paste(const Panel& panel, SelectionKind kind, StringType edit, StringType failToast, ItemsGet items_get) + { + auto text = panel.clipboard.get(); + auto& state = panel.state; + command_push(panel, + [&state, kind, edit, failToast, text, items_get](Document& document) + { + std::string errorString{}; + auto pasted = model::items_from_string(text, &errorString); + if (pasted.empty()) return toast_log(Level::ERROR, failToast, errorString); + document.edit_apply(edit, + [&](model::Model& model) + { + auto& items = items_get(model); + for (auto& item : pasted) + { + item.id = model::item_next_id_get(items); + items.push_back(std::move(item)); + } + }); + auto id = items_get(document.model).back().id; + document.selected_ids_set(kind, {id}); + document.focused_id_set(kind, id); + state.newId = id; + }); + } + + // Copy and paste for a content list, after a separator. + template + void items_clipboard_actions_add(Actions& actions, Panel& panel, SelectionKind kind, StringType pasteEdit, + StringType failToast, ItemsGet items_get) + { + auto selection = panel.document.selected_ids_get(kind); + actions.separator(); + actions.add( + ACTION_COPY, [selection]() { return !selection.empty(); }, + [&panel, selection, items_get]() { items_copy(panel.clipboard, items_get(panel.document.model), selection); }); + actions.add( + ACTION_PASTE, [&panel]() { return !panel.clipboard.is_empty(); }, + [&panel, kind, pasteEdit, failToast, items_get]() + { items_paste(panel, kind, pasteEdit, failToast, items_get); }); + } + + // Removes content items no animation (or layer, for spritesheets) uses. + template + void items_unused_remove(const Panel& panel, ElementType type, StringType edit, ItemsGet items_get) + { + command_push( + panel, + [type, edit, items_get](Document& document) + { + auto unused = document.model.unused_get(type); + if (unused.empty()) return; + document.edit_apply( + edit, [&](model::Model& model) + { std::erase_if(items_get(model), [&](const auto& item) { return unused.contains(item.id); }); }); + }); + } +} diff --git a/src/imgui/window/regions.cpp b/src/imgui/window/regions.cpp index dc1bd10..66d9022 100644 --- a/src/imgui/window/regions.cpp +++ b/src/imgui/window/regions.cpp @@ -1,11 +1,10 @@ -#include "window.hpp" +#include "panel.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" @@ -45,42 +44,40 @@ namespace anm2ed::imgui if (region.origin == Origin::CENTER) region.pivot = region.size * 0.5f; } - std::vector* regions_get(Document& document, model::Model& model) - { - auto spritesheet = model::item_get(model.content.spritesheets, document.spritesheet.reference); - return spritesheet ? &spritesheet->regions : nullptr; - } - const model::Spritesheet* region_spritesheet_get(Document& document) { - return model::item_get(document.model.content.spritesheets, document.spritesheet.reference); - } - - const model::Region* region_get(Document& document, int id) - { - auto spritesheet = region_spritesheet_get(document); - return spritesheet ? model::item_get(spritesheet->regions, id) : nullptr; + return model::item_get(document.model.content.spritesheets, document.focused_id_get(SelectionKind::SPRITESHEETS)); } + // New regions go after the last selected (or focused) one. int region_insert_index_get(Document& document) { auto spritesheet = region_spritesheet_get(document); - auto& storage = document.region; - int index = spritesheet ? (int)spritesheet->regions.size() : 0; - for (int i = 0; spritesheet && i < (int)spritesheet->regions.size(); i++) + if (!spritesheet) return 0; + auto selection = document.selected_ids_get(SelectionKind::REGIONS); + auto focus = document.focused_id_get(SelectionKind::REGIONS); + int index = (int)spritesheet->regions.size(); + for (int i = 0; i < (int)spritesheet->regions.size(); i++) { auto id = spritesheet->regions[i].id; - if (storage.selection.contains(id) || (storage.selection.empty() && storage.reference == id)) index = i + 1; + if (selection.contains(id) || (selection.empty() && focus == id)) index = i + 1; } return index; } - WindowCardImage region_image_get(Document& document, Resources& resources, int id) + void region_select(Document& document, int id) { - auto& region = *region_get(document, id); - 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}; + document.editTarget = Document::EditTarget::REGION; + document.selected_ids_set(SelectionKind::REGIONS, {id}); + document.focused_id_set(SelectionKind::REGIONS, id); + document.reference_set({document.reference_get().animationIndex}); + document.frame_references_clear(); + } + + CardImage region_image_get(Document& document, Resources& resources, const model::Region& region) + { + auto texture = document.texture_get(document.focused_id_get(SelectionKind::SPRITESHEETS)); + if (!texture || !texture->is_valid()) return {.texture = &resources.icons[icon::NONE], .size = region.size}; return {.texture = texture, .size = region.size, .uvMin = region.crop / vec2(texture->size), @@ -131,7 +128,7 @@ namespace anm2ed::imgui auto outputPath = options.path; if (!outputPath.empty()) { - outputPath = window_asset_path_get(document, outputPath.replace_extension(PNG_EXTENSION)); + outputPath = 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()); @@ -146,6 +143,14 @@ namespace anm2ed::imgui { document.edit_begin(EDIT_EXPORT_REGION); + if (options.isRemoveCurrent) + { + if (auto source = model::item_get(document.model.content.spritesheets, options.spritesheetId)) + std::erase_if(source->regions, [&](const model::Region& region) { return region.id == options.regionId; }); + edit::region_frames_sync(document.model); + document.selected_clear(SelectionKind::REGIONS); + } + if (options.isMakeSpritesheet) { auto& spritesheets = document.model.content.spritesheets; @@ -162,27 +167,15 @@ namespace anm2ed::imgui document.texture_set(exported.id, Image(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}; + document.selected_ids_set(SelectionKind::SPRITESHEETS, {exported.id}); + document.focused_id_set(SelectionKind::SPRITESHEETS, exported.id); + document.selected_ids_set(SelectionKind::REGIONS, {exportedRegion.id}); + document.focused_id_set(SelectionKind::REGIONS, exportedRegion.id); if (!outputPath.empty()) document.spritesheet_hash_set_saved(exported.id); else document.spritesheetSaveHashes[exported.id] = 0; } - - if (options.isRemoveCurrent) - { - if (auto source = model::item_get(document.model.content.spritesheets, options.spritesheetId)) - std::erase_if(source->regions, [&](const model::Region& region) { return region.id == options.regionId; }); - edit::region_frames_sync(document.model); - if (!options.isMakeSpritesheet) - { - document.region.reference = -1; - document.region.selection.clear(); - } - } document.change(); } @@ -190,15 +183,15 @@ namespace anm2ed::imgui return true; } - bool region_drag_drop_update(Window& window, Manager& manager, Document& document, int id, int index) + bool region_drag_drop_update(Panel& panel, int id, int index) { - auto& selection = document.region.selection; + auto& state = panel.state; + auto selection = panel.document.selected_ids_get(SelectionKind::REGIONS); if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) { - window.dragSelection = + state.dragIds = selection.contains(id) ? std::vector(selection.begin(), selection.end()) : std::vector{id}; - ImGui::SetDragDropPayload(REGION_DRAG_DROP, window.dragSelection.data(), - window.dragSelection.size() * sizeof(int)); + ImGui::SetDragDropPayload(REGION_DRAG_DROP, state.dragIds.data(), state.dragIds.size() * sizeof(int)); ImGui::EndDragDropSource(); } @@ -215,26 +208,25 @@ namespace anm2ed::imgui 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 (auto keyIndex = vector::find_index(state.keys, payloadIds[i]); keyIndex != -1) indices.push_back(keyIndex); 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 - { - if (!model::item_get(document.model.content.spritesheets, spritesheetId)) return; - document.edit_apply(EDIT_MOVE_REGIONS, - [&](model::Model& model) - { - auto spritesheet = model::item_get(model.content.spritesheets, spritesheetId); - vector::move_indices_to_position(spritesheet->regions, indices, targetIndex); - document.region.selection = std::set(movedIds.begin(), movedIds.end()); - }); - }}); + command_push(panel, + [indices, movedIds = state.dragIds, targetIndex = index + (isAfter ? 1 : 0), + spritesheetId = panel.document.focused_id_get(SelectionKind::SPRITESHEETS)](Document& document) + { + if (!model::item_get(document.model.content.spritesheets, spritesheetId)) return; + document.edit_apply( + EDIT_MOVE_REGIONS, + [&](model::Model& model) + { + auto spritesheet = model::item_get(model.content.spritesheets, spritesheetId); + vector::move_indices_to_position(spritesheet->regions, indices, targetIndex); + }); + document.selected_ids_set(SelectionKind::REGIONS, {movedIds.begin(), movedIds.end()}); + }); isMoved = true; } } @@ -242,281 +234,319 @@ namespace anm2ed::imgui return isMoved; } - void region_drag_tooltip_update(Window& window, Document& document) + void region_drag_tooltip_update(Panel& panel) { + auto& state = panel.state; auto payload = ImGui::GetDragDropPayload(); - auto spritesheet = region_spritesheet_get(document); + auto spritesheet = region_spritesheet_get(panel.document); if (!spritesheet || !payload || !payload->IsDataType(REGION_DRAG_DROP) || payload->IsDelivery() || - window.dragSelection.empty()) + state.dragIds.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::SetDragDropPayload(REGION_DRAG_DROP, state.dragIds.data(), state.dragIds.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) + for (auto regionId : state.dragIds) if (auto region = model::item_get(spritesheet->regions, 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 ? model::item_get(spritesheet->regions, 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.editRegion = target ? *target : model::Region{}; - if (window.popup.isJustOpened) window.isPreserveEditElementOnOpen = false; - auto& region = window.editRegion; - - 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_item_apply_push(window, manager, region, reference, regions_get, - region_insert_index_get(document)); - 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) + void region_properties_open(RegionsPanel& regions, Document& document, int id) { auto spritesheet = region_spritesheet_get(document); - auto regionId = window.editId != -1 ? window.editId : document.region.reference; - auto region = spritesheet && regionId != -1 ? model::item_get(spritesheet->regions, 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.icon_id_get(icon::FOLDER), 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(); + auto region = spritesheet ? model::item_get(spritesheet->regions, id) : nullptr; + if (id != -1 && !region) return; + regions.editId = id; + regions.editRegion = region ? *region : model::Region{}; + regions.propertiesPopup.open(); } - Window regions_window_register() + void region_properties_popup_update(Panel& panel, RegionsPanel& regions) { - Window window{}; - window.title = LABEL_REGIONS_WINDOW; - window.isOpen = &Settings::windowIsRegions; - 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.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_items_bind(window, regions_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) + auto& popup = regions.propertiesPopup; + popup.trigger(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + + auto& region = regions.editRegion; + if (ImGui::BeginChild("##Child", child_size_get(REGION_POPUP_ROWS), ImGuiChildFlags_Borders)) { - document.editTarget = Document::EditTarget::REGION; - document.reference_set({document.reference_get().animationIndex}); - document.frame_references_clear(); - }; - window.tooltip_draw = [](Document& document, Resources& resources, int id) + if (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 = popup_buttons_draw(panel.manager, localize.get(regions.editId == -1 ? BASIC_ADD : BASIC_CONFIRM)); + if (result == PopupButton::CONFIRM) { - auto& region = *region_get(document, id); - window_tooltip_image_draw( - region_image_get(document, resources, id), - [&]() - { - 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&) + auto& state = panel.state; + command_push(panel, + [&state, edited = region, id = regions.editId, insertIndex = region_insert_index_get(panel.document), + spritesheetId = panel.document.focused_id_get(SelectionKind::SPRITESHEETS)](Document& document) + { + auto changedId = id; + document.edit_apply(id == -1 ? EDIT_ADD_REGION : EDIT_SET_REGION_PROPERTIES, + [&](model::Model& model) + { + auto spritesheet = + model::item_get(model.content.spritesheets, spritesheetId); + if (!spritesheet) return; + auto& items = spritesheet->regions; + if (auto target = model::item_get(items, id)) + { + auto uid = target->uid; + *target = edited; + target->uid = uid; + target->id = id; + return; + } + if (id != -1) return; + changedId = model::item_next_id_get(items); + auto& added = *items.insert( + items.begin() + std::min(insertIndex, (int)items.size()), edited); + added.uid = util::uid_next(); + added.id = changedId; + state.newId = changedId; + }); + if (changedId != -1) region_select(document, changedId); + }); + } + if (result != PopupButton::NONE) popup.close(); + ImGui::EndPopup(); + popup.end(); + } + + void region_export_popup_update(Panel& panel, RegionsPanel& regions) + { + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto spritesheet = region_spritesheet_get(document); + auto region = spritesheet ? model::item_get(spritesheet->regions, regions.exportId) : nullptr; + auto& popup = regions.exportPopup; + + popup.trigger(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + + if (!region) popup.close(); + if (region && popup.isJustOpened) { - document.region.reference = -1; - window.editRegion = {}; - window.popup.open(); - }; - window.properties = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + 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 (dialog.is_selected(Dialog::REGION_EXPORT_PATH_SET)) { - auto& selection = document.region.selection; - if (selection.size() != 1 || !region_get(document, *selection.begin())) return; - document.region.reference = *selection.begin(); - window.popup.open(); - }; - window.export_open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + settings.exportRegionPath = dialog.path; + dialog.reset(); + } + + if (ImGui::BeginChild("##Export Region Child", child_size_get(REGION_POPUP_ROWS), ImGuiChildFlags_Borders)) { - window.editId = *document.region.selection.begin(); - window.popup2.open(); - }; - window.remove_unused = [](Window&, Manager&, Settings&, Document& document, Clipboard&) + if (ImGui::ImageButton("##Export Region Path Set", resources.icon_id_get(icon::FOLDER), icon_size_get())) + 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 spritesheetId = document.focused_id_get(SelectionKind::SPRITESHEETS); + auto texture = document.texture_get(spritesheetId); + auto isValid = region && texture && texture->is_valid() && !texture->pixels.empty() && + (settings.isExportRegionMakeSpritesheet || !settings.exportRegionPath.empty()); + auto result = popup_buttons_draw(manager, localize.get(BASIC_CONFIRM), isValid); + if (result == PopupButton::CONFIRM) { - document.edit_apply(EDIT_REMOVE_UNUSED_REGIONS, [&](model::Model& model) - { return edit::regions_remove_unused(model, document.spritesheet.reference); }); - }; - window.trim = [](Window&, Manager&, Settings&, Document& document, Clipboard&) + if (!settings.exportRegionPath.empty()) settings.exportRegionPath.replace_extension(PNG_EXTENSION); + RegionExportOptions options{.spritesheetId = spritesheetId, + .regionId = regions.exportId, + .path = settings.exportRegionPath, + .isMakeSpritesheet = settings.isExportRegionMakeSpritesheet, + .isRemoveCurrent = settings.isExportRegionRemoveCurrent}; + command_push(panel, + [&state, options](Document& document) + { + if (region_export(document, options) && options.isMakeSpritesheet) + state.newId = document.focused_id_get(SelectionKind::REGIONS); + }); + } + if (result != PopupButton::NONE) popup.close(); + ImGui::EndPopup(); + popup.end(); + } + + void regions_update(Panel& panel, RegionsPanel& regions) + { + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + if (manager.isMakeRegionRequested) { - auto& region = document.region; - document.edit_apply(EDIT_TRIM_REGIONS, - [&](model::Model&) - { - 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_set({document.reference_get().animationIndex}); - document.frame_references_clear(); - }); - }; - window.paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) + document.focused_id_set(SelectionKind::SPRITESHEETS, manager.makeRegionSpritesheetId); + regions.editId = -1; + regions.editRegion = manager.makeRegion; + regions.propertiesPopup.open(); + manager.isMakeRegionRequested = false; + } + + if (ImGui::Begin(localize.get(LABEL_REGIONS_WINDOW), &settings.windowIsRegions)) { auto spritesheet = region_spritesheet_get(document); - if (!spritesheet || clipboard.is_empty()) return; - auto maxIdBefore = model::item_next_id_get(spritesheet->regions) - 1; - std::string errorString{}; - document.edit_apply(EDIT_PASTE_REGIONS, - [&](model::Model& model) - { - edit::regions_paste(model, document.spritesheet.reference, clipboard.get(), - region_insert_index_get(document), &errorString); - auto target = region_spritesheet_get(document); - auto maxIdAfter = target ? model::item_next_id_get(target->regions) - 1 : -1; - if (maxIdAfter <= maxIdBefore) return; - window.newElementId = maxIdAfter; - document.region.selection = {maxIdAfter}; - document.region.reference = maxIdAfter; - }); - if (!errorString.empty()) toast_log(Level::ERROR, TOAST_DESERIALIZE_REGIONS_FAILED, errorString); - }; - 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_drag_tooltip_update(window, document); - }; - window.popup_update = - [](Window& window, Manager& manager, Settings& settings, Resources& resources, Clipboard&, Document& document) - { - if (manager.isMakeRegionRequested) + if (!spritesheet) + ImGui::TextUnformatted(localize.get(TEXT_SELECT_SPRITESHEET)); + else { - document.spritesheet.reference = manager.makeRegionSpritesheetId; - document.region.reference = -1; - window.editRegion = manager.makeRegion; - window.isPreserveEditElementOnOpen = true; - window.popup.open(); - manager.isMakeRegionRequested = false; + auto spritesheetId = spritesheet->id; + auto selection = document.selected_ids_get(SelectionKind::REGIONS); + auto isOne = [selection]() { return selection.size() == 1; }; + + Actions actions{}; + actions.add(ACTION_PROPERTIES, isOne, [&]() { region_properties_open(regions, document, *selection.begin()); }); + actions.add(ACTION_ADD, {}, [&]() { region_properties_open(regions, document, -1); }, TOOLTIP_ADD_REGION); + actions.add( + ACTION_REMOVE_UNUSED, {}, + [&]() + { + command_push(panel, + [spritesheetId](Document& document) + { + document.edit_apply(EDIT_REMOVE_UNUSED_REGIONS, [&](model::Model& model) + { return edit::regions_remove_unused(model, spritesheetId); }); + }); + }, + TOOLTIP_REMOVE_UNUSED_REGIONS); + actions.add( + ACTION_TRIM, [selection]() { return !selection.empty(); }, + [&]() + { + command_push(panel, + [spritesheetId, selection](Document& document) + { + document.edit_apply(EDIT_TRIM_REGIONS, + [&](model::Model&) + { + if (!document.regions_trim(spritesheetId, selection)) return; + document.reference_set({document.reference_get().animationIndex}); + document.frame_references_clear(); + }); + }); + }, + TOOLTIP_TRIM_REGIONS); + actions.add(ACTION_EXPORT, isOne, + [&]() + { + regions.exportId = *selection.begin(); + regions.exportPopup.open(); + }); + actions.separator(); + actions.add( + ACTION_COPY, [selection]() { return !selection.empty(); }, + [&]() { items_copy(clipboard, spritesheet->regions, selection); }); + actions.add( + ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, + [&]() + { + command_push( + panel, + [&state, spritesheetId, text = clipboard.get(), + insertIndex = region_insert_index_get(document)](Document& document) + { + auto spritesheet_regions_get = [&]() -> const std::vector* + { + auto spritesheet = model::item_get(document.model.content.spritesheets, spritesheetId); + return spritesheet ? &spritesheet->regions : nullptr; + }; + if (!spritesheet_regions_get()) return; + auto nextId = model::item_next_id_get(*spritesheet_regions_get()); + std::string errorString{}; + document.edit_apply( + EDIT_PASTE_REGIONS, [&](model::Model& model) + { return edit::regions_paste(model, spritesheetId, text, insertIndex, &errorString); }); + if (!errorString.empty()) toast_log(Level::ERROR, TOAST_DESERIALIZE_REGIONS_FAILED, errorString); + auto lastId = model::item_next_id_get(*spritesheet_regions_get()) - 1; + if (lastId < nextId) return; + state.newId = lastId; + region_select(document, lastId); + }); + }); + + ListRows rows{.label_get = [&](int id) { return model::item_get(spritesheet->regions, id)->name; }, + .tooltip_draw = + [&](int id) + { + auto& region = *model::item_get(spritesheet->regions, id); + tooltip_image_draw( + region_image_get(document, resources, region), + [&]() + { + 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()); + }); + }, + .image_get = [&](int id) + { return region_image_get(document, resources, *model::item_get(spritesheet->regions, id)); }, + .select = + [&](int) + { + document.editTarget = Document::EditTarget::REGION; + document.reference_set({document.reference_get().animationIndex}); + document.frame_references_clear(); + }, + .activate = [&](int id) { region_properties_open(regions, document, id); }, + .drag_drop_update = [&](int id, int index) { return region_drag_drop_update(panel, id, index); }, + .cardLines = REGION_CARD_LINES}; + list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_EXPORT, ACTION_REMOVE_UNUSED}}, + [&]() + { + content_list_draw(panel, SelectionKind::REGIONS, item_ids_get(spritesheet->regions), rows); + region_drag_tooltip_update(panel); + }); } - region_properties_popup_update(window, manager, document); - region_export_popup_update(window, manager, settings, resources, document); - }; - return window; + } + ImGui::End(); + + region_properties_popup_update(panel, regions); + region_export_popup_update(panel, regions); } } diff --git a/src/imgui/window/shaders.cpp b/src/imgui/window/shaders.cpp index ac5e4bc..08f3ba1 100644 --- a/src/imgui/window/shaders.cpp +++ b/src/imgui/window/shaders.cpp @@ -17,6 +17,8 @@ using namespace anm2ed::util; namespace anm2ed::imgui { + constexpr int SHADER_CARD_LINES = 2; + #define SHADER_UNIFORM_BINDING_COMBO_VALUES \ X(resource::shader::UNIFORM_BINDING_IGNORE) \ X(resource::shader::UNIFORM_BINDING_MANUAL) \ @@ -74,7 +76,7 @@ namespace anm2ed::imgui } } - void shader_dialog_update(ShadersWindow& window, Manager& manager, Dialog& dialog, Dialog::Type type, + void shader_dialog_update(ShadersPanel& window, Manager& manager, Dialog& dialog, Dialog::Type type, std::filesystem::path model::Shader::* member) { if (!dialog.is_selected(type)) return; @@ -88,7 +90,7 @@ namespace anm2ed::imgui dialog.reset(); } - void shader_path_row_update(ShadersWindow& window, Document& document, Resources& resources, Dialog& dialog, + void shader_path_row_update(ShadersPanel& window, Document& document, Resources& resources, Dialog& dialog, model::Shader* shader, std::filesystem::path model::Shader::* member, Dialog::Type dialogType, StringType label) { @@ -287,210 +289,105 @@ namespace anm2ed::imgui ImGui::EndTable(); } - void ShadersWindow::update(Manager& manager, Settings& settings, Resources& resources, Dialog& dialog) + auto& shaders_get(model::Model& model) { return model.content.shaders; } + + void shaders_update(Panel& panel, ShadersPanel& shaders) { + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& items = document.model.content.shaders; + auto& status = shaders.status; + auto& propertiesPopup = shaders.propertiesPopup; + auto& popupShaderId = shaders.popupShaderId; + shader_dialog_update(shaders, manager, dialog, Dialog::SHADER_VERTEX_PATH_SET, &model::Shader::vertex); + shader_dialog_update(shaders, manager, dialog, Dialog::SHADER_FRAGMENT_PATH_SET, &model::Shader::fragment); + if (ImGui::Begin(localize.get(LABEL_SHADERS_WINDOW), &settings.windowIsShaders)) { - auto document = manager.get(); - if (!document) + auto selection = document.selected_ids_get(SelectionKind::SHADERS); + auto properties_open = [&](int id) { - ImGui::End(); - return; - } - auto shaders = &document->model.content.shaders; - - shader_dialog_update(*this, manager, dialog, Dialog::SHADER_VERTEX_PATH_SET, &model::Shader::vertex); - shader_dialog_update(*this, manager, dialog, Dialog::SHADER_FRAGMENT_PATH_SET, &model::Shader::fragment); - - auto shader_add = [&]() - { - manager.command_push({manager.selected, [this](Manager&, Document& document) - { - document.edit_apply(EDIT_ADD_SHADER, - [&](model::Model& model) - { - auto& shaders = model.content.shaders; - auto& shader = shaders.emplace_back( - model::Shader{.id = model::item_next_id_get(shaders), - .name = localize.get(TEXT_NEW_SHADER)}); - document.shader.selection = {shader.id}; - document.shader.reference = shader.id; - newElementId = shader.id; - }); - }}); + document.selected_ids_set(SelectionKind::SHADERS, {id}); + popupShaderId = id; + propertiesPopup.open(); }; - auto unused_shaders_remove = [&]() - { - manager.command_push({manager.selected, [this](Manager&, Document& document) - { - auto unused = document.model.unused_get(ElementType::SHADER); - if (unused.empty()) return; - - document.edit_apply(EDIT_REMOVE_UNUSED_SHADERS, - [&](model::Model& model) - { - std::erase_if(model.content.shaders, - [&](const model::Shader& shader) - { return unused.contains(shader.id); }); - for (auto id : unused) - { - document.shader.selection.erase(id); - if (document.shader.reference == id) - document.shader.reference = -1; - if (popupShaderId == id) propertiesPopup.close(); - } - }); - }}); - }; - - auto& selection = document->shader.selection; - auto& reference = document->shader.reference; - std::vector ids{}; - for (auto& shader : *shaders) - ids.push_back(shader.id); - - if (reference != -1 && !model::item_get(*shaders, reference)) reference = -1; - for (auto it = selection.begin(); it != selection.end();) - { - if (!model::item_get(*shaders, *it)) - it = selection.erase(it); - else - ++it; - } - - auto contentSize = size_without_footer_get(); - if (contentSize.y < ImGui::GetFrameHeight()) contentSize.y = ImGui::GetFrameHeight(); - auto tooltipWindowPadding = ImGui::GetStyle().WindowPadding; - auto tooltipItemSpacing = ImGui::GetStyle().ItemSpacing; - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - if (ImGui::BeginChild("##Shaders Child", contentSize, ImGuiChildFlags_Borders)) - { - auto style = ImGui::GetStyle(); - auto shaderChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 2); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); - selection.start(ids.size()); - 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; - } - - for (auto& shader : *shaders) - { - auto id = shader.id; - auto isNewShader = newElementId == id; - ImGui::PushID(id); - - if (ImGui::BeginChild("##Shader Child", shaderChildSize, ImGuiChildFlags_Borders)) + Actions actions{}; + actions.add( + ACTION_ADD, {}, + [&]() { - auto isSelected = selection.contains(id); - auto cursorPos = ImGui::GetCursorPos(); - auto runtime = document->shader_get(id); - bool isValid = runtime != nullptr; - auto& shaderIcon = isValid ? resources.icons[icon::SHADER] : 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); - - ImGui::SetNextItemSelectionUserData(id); - ImGui::SetNextItemStorageID(id); - auto isActivated = ImGui::Selectable("##Shader Selectable", isSelected, 0, shaderChildSize); - auto isClicked = - ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); - if (isActivated || isClicked) reference = id; - if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) - { - selection = {id}; - reference = id; - popupShaderId = id; - propertiesPopup.open(); - } - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, tooltipItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, tooltipWindowPadding); - if (ImGui::BeginItemTooltip()) - { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(shader.name.c_str()); - ImGui::PopFont(); - ImGui::Text("%s: %d", localize.get(BASIC_ID), id); - ImGui::Text("%s: %s", localize.get(LABEL_VERTEX), path::to_utf8(shader.vertex).c_str()); - ImGui::Text("%s: %s", localize.get(LABEL_FRAGMENT), path::to_utf8(shader.fragment).c_str()); - if (!isValid) + command_push(panel, + [&state](Document& document) + { + int id{}; + document.edit_apply(EDIT_ADD_SHADER, + [&](model::Model& model) + { + auto& shaders = model.content.shaders; + id = model::item_next_id_get(shaders); + shaders.push_back({.id = id, .name = localize.get(TEXT_NEW_SHADER)}); + }); + document.selected_ids_set(SelectionKind::SHADERS, {id}); + document.focused_id_set(SelectionKind::SHADERS, id); + state.newId = id; + }); + }, + TOOLTIP_ADD_SHADER); + actions.add( + ACTION_REMOVE_UNUSED, {}, + [&]() { items_unused_remove(panel, ElementType::SHADER, EDIT_REMOVE_UNUSED_SHADERS, shaders_get); }, + TOOLTIP_REMOVE_UNUSED_SHADERS); + actions.add( + ACTION_RELOAD, [selection]() { return !selection.empty(); }, + [&]() + { + status.clear(); + for (auto id : selection) + if (auto shader = shader_element_get(document, id)) { - ImGui::Spacing(); - ImGui::TextWrapped("%s", localize.get(TOOLTIP_SHADER_INVALID)); + document.shader_reload(id, &status); + toasts.push(std::vformat(localize.get(TOAST_RELOAD_SHADER), std::make_format_args(id, shader->name))); } - ImGui::EndTooltip(); - } - ImGui::PopStyleVar(2); + }, + TOOLTIP_RELOAD_SHADERS); - ImGui::SetCursorPos(cursorPos); - auto imageSize = ImVec2(shaderChildSize.y, shaderChildSize.y); - ImGui::ImageWithBg(resource::texture::id_get(shaderIcon), imageSize, ImVec2(), ImVec2(1, 1), ImVec4(), - tintColor); - - ImGui::SetCursorPos(ImVec2(shaderChildSize.y + style.ItemSpacing.x, - shaderChildSize.y - shaderChildSize.y / 2 - ImGui::GetTextLineHeight() / 2)); - auto label = std::vformat(localize.get(FORMAT_SHADER), std::make_format_args(id, shader.name)); - ImGui::TextUnformatted(label.c_str()); - } - ImGui::EndChild(); - - if (isNewShader) - { - ImGui::SetScrollHereY(0.5f); - newElementId = -1; - } - - ImGui::PopID(); - } - - selection.finish(); - ImGui::PopStyleVar(); - } - ImGui::EndChild(); - ImGui::PopStyleVar(); - - auto widgetSize = widget_size_with_row_get(3); - if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) shader_add(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ADD_SHADER)); - - ImGui::SameLine(); - - if (ImGui::Button(localize.get(BASIC_REMOVE_UNUSED), widgetSize)) unused_shaders_remove(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REMOVE_UNUSED_SHADERS)); - - ImGui::SameLine(); - - ImGui::BeginDisabled(selection.empty()); - if (ImGui::Button(localize.get(BASIC_RELOAD), widgetSize)) + auto image_get = [&](int id) { - status.clear(); - for (auto id : selection) - { - auto shader = shader_element_get(*document, id); - if (!shader) continue; - document->shader_reload(id, &status); - toasts.push(std::vformat(localize.get(TOAST_RELOAD_SHADER), std::make_format_args(id, shader->name))); - } - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RELOAD_SHADERS)); - ImGui::EndDisabled(); + auto isValid = document.shader_get(id) != nullptr; + auto& image = resources.icons[isValid ? icon::SHADER : icon::NONE]; + return CardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}; + }; + ListRows rows{.label_get = + [&](int id) + { + auto name = shader_element_get(document, id)->name; + return std::vformat(localize.get(FORMAT_SHADER), std::make_format_args(id, name)); + }, + .tooltip_draw = + [&](int id) + { + auto& shader = *shader_element_get(document, id); + tooltip_name_draw(resources, shader.name); + ImGui::Text("%s: %d", localize.get(BASIC_ID), id); + ImGui::Text("%s: %s", localize.get(LABEL_VERTEX), path::to_utf8(shader.vertex).c_str()); + ImGui::Text("%s: %s", localize.get(LABEL_FRAGMENT), path::to_utf8(shader.fragment).c_str()); + if (image_get(id).isValid) return; + ImGui::Spacing(); + ImGui::TextWrapped("%s", localize.get(TOOLTIP_SHADER_INVALID)); + }, + .image_get = image_get, + .activate = properties_open, + .cardLines = SHADER_CARD_LINES}; + list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED, ACTION_RELOAD}}, + [&]() { content_list_draw(panel, SelectionKind::SHADERS, item_ids_get(items), rows); }); propertiesPopup.trigger(); if (ImGui::BeginPopupModal(propertiesPopup.label(), &propertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) { - auto shader = shader_element_get(*document, popupShaderId); + auto shader = shader_element_get(document, popupShaderId); + if (!shader) propertiesPopup.close(); if (!shader) { - propertiesPopup.close(); ImGui::EndPopup(); propertiesPopup.end(); ImGui::End(); @@ -502,27 +399,27 @@ namespace anm2ed::imgui if (ImGui::BeginChild("##Shader Properties Child", popupSize)) { if (propertiesPopup.isJustOpened) ImGui::SetKeyboardFocusHere(); - if (input_text_string(localize.get(BASIC_NAME), &shader->name)) document->change(); + if (input_text_string(localize.get(BASIC_NAME), &shader->name)) document.change(); ImGui::SeparatorText(localize.get(LABEL_FILES)); - shader_path_row_update(*this, *document, resources, dialog, shader, &model::Shader::vertex, + shader_path_row_update(shaders, document, resources, dialog, shader, &model::Shader::vertex, Dialog::SHADER_VERTEX_PATH_SET, LABEL_VERTEX); - shader_path_row_update(*this, *document, resources, dialog, shader, &model::Shader::fragment, + shader_path_row_update(shaders, document, resources, dialog, shader, &model::Shader::fragment, Dialog::SHADER_FRAGMENT_PATH_SET, LABEL_FRAGMENT); - if (is_shader_reload_needed(*document, shader)) + if (is_shader_reload_needed(document, shader)) ImGui::TextWrapped("%s", localize.get(LABEL_SHADER_RELOAD_NEEDED)); ImGui::SeparatorText(localize.get(LABEL_UNIFORMS)); - auto runtime = document->shader_get(shader->id); + auto runtime = document.shader_get(shader->id); auto tableSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 8.0f); auto outputReserve = ImGui::GetTextLineHeightWithSpacing() * 6.0f; auto availableHeight = ImGui::GetContentRegionAvail().y; if (availableHeight - outputReserve < tableSize.y) tableSize.y = availableHeight - outputReserve; if (tableSize.y < ImGui::GetFrameHeight()) tableSize.y = ImGui::GetFrameHeight(); - shader_uniforms_update(*document, shader, runtime, tableSize); + shader_uniforms_update(document, shader, runtime, tableSize); ImGui::SeparatorText(localize.get(LABEL_OUTPUT)); @@ -538,7 +435,7 @@ namespace anm2ed::imgui if (ImGui::Button(localize.get(BASIC_CONFIRM), popupWidgetSize)) { status.clear(); - document->shader_reload(shader->id, &status); + document.shader_reload(shader->id, &status); propertiesPopup.close(); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RELOAD_SHADERS)); diff --git a/src/imgui/window/shaders.hpp b/src/imgui/window/shaders.hpp index 860f368..0a7c74d 100644 --- a/src/imgui/window/shaders.hpp +++ b/src/imgui/window/shaders.hpp @@ -1,21 +1,17 @@ #pragma once -#include "dialog.hpp" -#include "manager.hpp" -#include "resources.hpp" -#include "settings.hpp" -#include "util/imgui/popup.hpp" +#include "panel.hpp" namespace anm2ed::imgui { - class ShadersWindow + struct ShadersPanel { - public: + PanelState state{}; std::string status{}; int dialogShaderId{-1}; int popupShaderId{-1}; - int newElementId{-1}; PopupHelper propertiesPopup{PopupHelper(LABEL_SHADER_PROPERTIES, POPUP_NORMAL)}; - void update(Manager&, Settings&, Resources&, Dialog&); }; + + void shaders_update(Panel&, ShadersPanel&); } diff --git a/src/imgui/window/sounds.cpp b/src/imgui/window/sounds.cpp index e67602d..8848f5d 100644 --- a/src/imgui/window/sounds.cpp +++ b/src/imgui/window/sounds.cpp @@ -1,9 +1,8 @@ -#include "window.hpp" +#include "panel.hpp" #include #include "path.hpp" -#include "toast.hpp" using namespace anm2ed::resource; using namespace anm2ed::types; @@ -13,121 +12,128 @@ namespace anm2ed::imgui { constexpr int SOUND_CARD_LINES = 2; - std::vector* sounds_get(Document&, model::Model& model) { return &model.content.sounds; } + auto& sounds_get(model::Model& model) { return model.content.sounds; } - Window sounds_window_register() + void sounds_update(Panel& panel) { - Window window{}; - window.title = LABEL_SOUNDS_WINDOW; - window.isOpen = &Settings::windowIsSounds; - 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_items_bind(window, sounds_get); - window.row_label_get = [](Document& document, int id) - { - auto pathString = path::to_utf8(model::item_get(document.model.content.sounds, id)->path); - return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)); - }; - window.row_select = [](Window&, Document& document, int id) - { - if (auto audio = document.sound_get(id); audio && ImGui::IsItemClicked(ImGuiMouseButton_Left)) - resource::audio::play(*audio); - }; - window.card_image_get = [](Document& document, Resources& resources, int id) - { - auto audio = document.sound_get(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, int id) - { - auto audio = document.sound_get(id); - window_tooltip_name_draw(resources, path::to_utf8(model::item_get(document.model.content.sounds, id)->path)); - ImGui::Text("%s: %d", localize.get(BASIC_ID), 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())) resource::audio::play(*audio); - }; - window.open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - auto sound = model::item_get(document.model.content.sounds, document.sound.reference); - if (sound && window.dialog) window_directory_open(*window.dialog, document, sound->path); - }; - window.reload = [](Window&, Manager&, Settings&, Document& document, Clipboard&) - { - document.edit_apply(EDIT_RELOAD_SOUNDS, - [&](model::Model& model) - { - for (auto id : document.sound.selection) - if (auto sound = model::item_get(model.content.sounds, 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(); - } + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& sounds = document.model.content.sounds; + auto selection = document.selected_ids_get(SelectionKind::SOUNDS); - if (window.dialog->is_selected(Dialog::SOUND_REPLACE)) + if (dialog.is_selected(Dialog::SOUND_OPEN)) + { + command_push(panel, + [&state, paths = dialog.paths](Document& document) + { + document.sounds_add(paths); + state.newId = document.focused_id_get(SelectionKind::SOUNDS); + }); + dialog.reset(); + } + + if (dialog.is_selected(Dialog::SOUND_REPLACE)) + { + if (selection.size() == 1 && !dialog.path.empty()) + command_push(panel, + [id = *selection.begin(), dialogPath = dialog.path](Document& document) + { + if (!model::item_get(document.model.content.sounds, id)) return; + document.edit_apply(EDIT_REPLACE_SOUND, + [&](model::Model& model) + { + auto sound = model::item_get(model.content.sounds, id); + sound->path = asset_path_get(document, dialogPath); + document.sound_reload(id); + toast_log(Level::INFO, TOAST_REPLACE_SOUND, id, + path::to_utf8(sound->path)); + }); + }); + dialog.reset(); + } + + if (ImGui::Begin(localize.get(LABEL_SOUNDS_WINDOW), &settings.windowIsSounds)) + { + auto isOne = [selection]() { return selection.size() == 1; }; + auto play = [&](int id) { - 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) - { - if (!model::item_get(document.model.content.sounds, id)) return; - document.edit_apply(EDIT_REPLACE_SOUND, - [&](model::Model& model) - { - auto sound = model::item_get(model.content.sounds, id); - 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; + if (auto audio = document.sound_get(id)) resource::audio::play(*audio); + }; + auto open = [&](int id) + { + if (auto sound = model::item_get(sounds, id)) directory_open(dialog, document, sound->path); + }; + + Actions actions{}; + actions.add(ACTION_PLAY, isOne, [&]() { play(*selection.begin()); }, STRING_UNDEFINED, -1); + actions.add(ACTION_OPEN_DIRECTORY, isOne, [&]() { open(*selection.begin()); }); + actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::SOUND_OPEN, true); }, TOOLTIP_SOUND_ADD); + actions.add( + ACTION_REMOVE_UNUSED, {}, + [&]() { items_unused_remove(panel, ElementType::SOUND_ELEMENT, EDIT_REMOVE_UNUSED_SOUNDS, sounds_get); }, + TOOLTIP_REMOVE_UNUSED_SOUNDS); + actions.add( + ACTION_RELOAD, [selection]() { return !selection.empty(); }, + [&]() + { + command_push(panel, + [selection](Document& document) + { + document.edit_apply(EDIT_RELOAD_SOUNDS, + [&](model::Model& model) + { + for (auto id : selection) + if (auto sound = model::item_get(model.content.sounds, id)) + { + document.sound_reload(id); + toast_log(Level::INFO, TOAST_RELOAD_SOUND, id, + path::to_utf8(sound->path)); + } + }); + }); + }, + TOOLTIP_RELOAD_SOUNDS); + actions.add(ACTION_REPLACE, isOne, [&]() { dialog.file_open(Dialog::SOUND_REPLACE); }, TOOLTIP_REPLACE_SOUND); + items_clipboard_actions_add(actions, panel, SelectionKind::SOUNDS, TOAST_SOUNDS_PASTE, + TOAST_SOUNDS_DESERIALIZE_ERROR, sounds_get); + + ListRows rows{.label_get = + [&](int id) + { + auto pathString = path::to_utf8(model::item_get(sounds, id)->path); + return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)); + }, + .tooltip_draw = + [&](int id) + { + auto audio = document.sound_get(id); + tooltip_name_draw(resources, path::to_utf8(model::item_get(sounds, id)->path)); + ImGui::Text("%s: %d", localize.get(BASIC_ID), id); + if (audio && audio->is_valid()) + ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); + else + { + ImGui::Spacing(); + ImGui::TextWrapped("%s", localize.get(TOOLTIP_SOUND_INVALID)); + } + }, + .image_get = + [&](int id) + { + auto audio = document.sound_get(id); + auto isValid = audio && audio->is_valid(); + auto& texture = resources.icons[isValid ? icon::SOUND : icon::NONE]; + return CardImage{.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid}; + }, + .select = + [&](int id) + { + if (id != -1 && ImGui::IsItemClicked(ImGuiMouseButton_Left)) play(id); + }, + .activate = open, + .cardLines = SOUND_CARD_LINES}; + list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED, ACTION_RELOAD, ACTION_REPLACE}}, + [&]() { content_list_draw(panel, SelectionKind::SOUNDS, item_ids_get(sounds), rows); }); + } + ImGui::End(); } } diff --git a/src/imgui/window/spritesheet_editor.cpp b/src/imgui/window/spritesheet_editor.cpp index 6ed479d..af375b2 100644 --- a/src/imgui/window/spritesheet_editor.cpp +++ b/src/imgui/window/spritesheet_editor.cpp @@ -32,7 +32,7 @@ namespace anm2ed::imgui auto& document = *manager.get(); auto& model = document.model; auto reference = document.reference_get(); - auto& referenceSpritesheet = document.spritesheet.reference; + auto referenceSpritesheet = document.focused_id_get(SelectionKind::SPRITESHEETS); auto& pan = document.editorPan; auto& zoom = document.editorZoom; auto& backgroundColor = settings.editorBackgroundColor; @@ -58,7 +58,10 @@ namespace anm2ed::imgui if (auto selectedLayerSpritesheet = selected_layer_spritesheet_get(); selectedLayerSpritesheet != -1 && document.editTarget != Document::EditTarget::REGION && document.editTarget != Document::EditTarget::SPRITESHEET) + { referenceSpritesheet = selectedLayerSpritesheet; + document.focused_id_set(SelectionKind::SPRITESHEETS, referenceSpritesheet); + } auto spritesheet = model::item_get(model.content.spritesheets, referenceSpritesheet); auto baseTexture = document.texture_get(referenceSpritesheet); auto texture = baseTexture; @@ -67,8 +70,8 @@ namespace anm2ed::imgui auto& shaderTexture = resources.shaders[shader::TEXTURE]; auto& shaderLine = resources.shaders[shader::LINE]; auto& dashedShader = resources.shaders[shader::DASHED]; - auto& regionReference = document.region.reference; - auto& regionSelection = document.region.selection; + auto regionReference = document.focused_id_get(SelectionKind::REGIONS); + auto regionSelection = document.selected_ids_get(SelectionKind::REGIONS); auto center_view = [&]() { pan = -size * 0.5f; }; @@ -546,12 +549,8 @@ namespace anm2ed::imgui document.editTarget = Document::EditTarget::REGION; regionReference = id; regionSelection = {id}; - manager.command_push({manager.selected, [=](Manager&, Document& document) - { - document.editTarget = Document::EditTarget::REGION; - document.region.reference = id; - document.region.selection = {id}; - }}); + document.selected_ids_set(SelectionKind::REGIONS, {id}); + document.focused_id_set(SelectionKind::REGIONS, id); }; auto region_pivot_set = [&](int id, vec2 pivot) { diff --git a/src/imgui/window/spritesheets.cpp b/src/imgui/window/spritesheets.cpp index 5d7d2f6..ceb3f2c 100644 --- a/src/imgui/window/spritesheets.cpp +++ b/src/imgui/window/spritesheets.cpp @@ -1,9 +1,8 @@ -#include "window.hpp" +#include "panel.hpp" #include #include "path.hpp" -#include "toast.hpp" #include "util/imgui/input.hpp" #include "util/imgui/layout.hpp" #include "working_directory.hpp" @@ -18,10 +17,7 @@ namespace anm2ed::imgui constexpr int MERGE_OPTIONS_ROWS = 6; constexpr int PADDING_MAX = 100; - std::vector* spritesheets_get(Document&, model::Model& model) - { - return &model.content.spritesheets; - } + auto& spritesheets_get(model::Model& model) { return model.content.spritesheets; } const model::Spritesheet* spritesheet_get(Document& document, int id) { @@ -51,40 +47,34 @@ namespace anm2ed::imgui } } - void spritesheet_path_change(Window& window, Manager& manager, int id, const std::filesystem::path& dialogPath, - StringType edit, bool isWritten) + // Points a spritesheet at a new file: replacing loads it, setting the path writes the current texture there. + void spritesheet_path_change(Document& document, 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 texture = document.texture_get(id); + if (!spritesheet_get(document, id) || (isWritten && !texture)) return; + document.edit_apply(edit, + [&](model::Model& model) + { + auto spritesheet = model::item_get(model.content.spritesheets, id); + auto newPath = asset_path_get(document, dialogPath); + auto pathString = path::to_utf8(newPath); + if (isWritten) { - auto texture = document.texture_get(id); - if (!spritesheet_get(document, id) || (isWritten && !texture)) return; - document.edit_apply( - edit, - [&](model::Model& model) - { - auto spritesheet = model::item_get(model.content.spritesheets, id); - 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); - }); - }}); + WorkingDirectory workingDirectory(document.directory_get()); + path::ensure_directory(newPath.parent_path()); + if (!texture->write_png(newPath)) + return toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); + } + 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, const std::function& behavior, @@ -96,283 +86,291 @@ namespace anm2ed::imgui document.change(); } - Window spritesheets_window_register() + void spritesheets_dialog_update(Panel& panel) { - Window window{}; - window.title = LABEL_SPRITESHEETS_WINDOW; - window.isOpen = &Settings::windowIsSpritesheets; - 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_items_bind(window, spritesheets_get); - window.row_label_get = [](Document& document, int id) + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + if (dialog.is_selected(Dialog::SPRITESHEET_OPEN)) { - auto pathString = path::to_utf8(spritesheet_get(document, id)->path); - auto label = std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(id, pathString)); - return document.spritesheet_is_dirty(id) - ? std::vformat(localize.get(FORMAT_SPRITESHEET_NOT_SAVED), std::make_format_args(label)) - : label; - }; - window.row_select = [](Window&, Document& document, int) + command_push(panel, + [&state, paths = dialog.paths](Document& document) + { + document.spritesheets_add(paths); + document.selected_clear(SelectionKind::REGIONS); + state.newId = document.focused_id_get(SelectionKind::SPRITESHEETS); + }); + dialog.reset(); + } + + auto selection = document.selected_ids_get(SelectionKind::SPRITESHEETS); + for (auto [type, edit] : {std::pair{Dialog::SPRITESHEET_REPLACE, EDIT_REPLACE_SPRITESHEET}, + std::pair{Dialog::SPRITESHEET_PATH_SET, EDIT_SET_SPRITESHEET_FILE_PATH}}) { - document.editTarget = Document::EditTarget::SPRITESHEET; - document.region.reference = -1; - document.region.selection.clear(); - }; - window.card_image_get = [](Document& document, Resources& resources, int id) + if (!dialog.is_selected(type)) continue; + if (selection.size() == 1 && !dialog.path.empty()) + command_push(panel, [id = *selection.begin(), path = dialog.path, edit, + isWritten = type == Dialog::SPRITESHEET_PATH_SET](Document& document) + { spritesheet_path_change(document, id, path, edit, isWritten); }); + dialog.reset(); + } + } + + void spritesheets_merge_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) + { + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& popup = spritesheets.mergePopup; + popup.trigger(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + + 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)) { - auto texture = document.texture_get(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, int id) + 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 = popup_buttons_draw(manager, localize.get(BASIC_MERGE), spritesheets.mergeIds.size() > 1); + if (result == PopupButton::CONFIRM) + command_push(panel, + [ids = spritesheets.mergeIds, isAppendRight = settings.mergeSpritesheetsOrigin == APPEND_RIGHT, + isMakeRegions = settings.mergeSpritesheetsIsMakeRegions, + isMakePrimaryRegion = settings.mergeSpritesheetsIsMakePrimaryRegion, + regionOrigin = (origin::Type)settings.mergeSpritesheetsRegionOrigin](Document& document) + { + spritesheet_textures_edit( + document, EDIT_MERGE_SPRITESHEETS, + [&]() + { + if (!document.spritesheets_merge(ids, isAppendRight, isMakeRegions, isMakePrimaryRegion, + regionOrigin)) + return false; + document.selected_ids_set(SelectionKind::SPRITESHEETS, {*ids.begin()}); + document.focused_id_set(SelectionKind::SPRITESHEETS, *ids.begin()); + document.selected_clear(SelectionKind::REGIONS); + return true; + }, + TOAST_MERGE_SPRITESHEETS, TOAST_MERGE_SPRITESHEETS_FAILED); + }); + if (result != PopupButton::NONE) popup.close(); + ImGui::EndPopup(); + popup.end(); + } + + void spritesheets_pack_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) + { + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& popup = spritesheets.packPopup; + popup.trigger(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + + 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 = + popup_buttons_draw(manager, localize.get(BASIC_PACK), is_spritesheet_regions(document, spritesheets.packId)); + if (result == PopupButton::CONFIRM) + command_push(panel, + [id = spritesheets.packId, padding = settings.packPadding](Document& document) + { + spritesheet_textures_edit( + document, EDIT_PACK_SPRITESHEET, [&]() { return document.spritesheet_pack(id, padding); }, + TOAST_PACK_SPRITESHEET, TOAST_PACK_SPRITESHEET_FAILED); + }); + if (result != PopupButton::NONE) popup.close(); + ImGui::EndPopup(); + popup.end(); + } + + void spritesheets_overwrite_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) + { + auto& popup = spritesheets.overwritePopup; + popup.trigger(); + if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); + + ImGui::TextUnformatted(localize.get(LABEL_OVERWRITE_CONFIRMATION)); + auto result = popup_buttons_draw(panel.manager, localize.get(BASIC_YES), true, BASIC_NO); + if (result == PopupButton::CONFIRM) + command_push(panel, [ids = spritesheets.saveIds](Document& document) { spritesheets_save(document, ids); }); + if (result != PopupButton::NONE) popup.close(); + ImGui::EndPopup(); + popup.end(); + } + + void spritesheets_update(Panel& panel, SpritesheetsPanel& spritesheets) + { + auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; + auto& items = document.model.content.spritesheets; + spritesheets_dialog_update(panel); + + if (ImGui::Begin(localize.get(LABEL_SPRITESHEETS_WINDOW), &settings.windowIsSpritesheets)) { - auto& spritesheet = *spritesheet_get(document, id); - auto texture = document.texture_get(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}, + auto selection = document.selected_ids_get(SelectionKind::SPRITESHEETS); + auto isOne = [selection]() { return selection.size() == 1; }; + auto isAny = [selection]() { return !selection.empty(); }; + auto open = [&](int id) + { + if (auto spritesheet = spritesheet_get(document, id)) directory_open(dialog, document, spritesheet->path); + }; + + Actions actions{}; + actions.add(ACTION_OPEN_DIRECTORY, isOne, [&]() { open(*selection.begin()); }); + actions.add(ACTION_SET_FILE_PATH, isOne, [&]() { dialog.file_save(Dialog::SPRITESHEET_PATH_SET); }); + actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::SPRITESHEET_OPEN, true); }, TOOLTIP_ADD_SPRITESHEET); + actions.add( + ACTION_REMOVE_UNUSED, {}, [&]() { - 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)); + command_push(panel, + [](Document& document) + { + auto unused = document.model.unused_get(ElementType::SPRITESHEET); + if (unused.empty()) return; + document.edit_apply(EDIT_REMOVE_UNUSED_SPRITESHEETS, + [&](model::Model& model) + { + std::erase_if(model.content.spritesheets, + [&](const model::Spritesheet& spritesheet) + { + if (!unused.contains(spritesheet.id)) return false; + toast_log(Level::INFO, TOAST_REMOVE_SPRITESHEET, + spritesheet.id, + path::to_utf8(spritesheet.path)); + return true; + }); + }); + }); + }, + TOOLTIP_REMOVE_UNUSED_SPRITESHEETS); + actions.add( + ACTION_RELOAD, isAny, + [&]() + { + command_push(panel, + [selection](Document& document) + { + document.edit_apply(EDIT_RELOAD_SPRITESHEETS, + [&](model::Model&) + { + for (auto id : selection) + document.texture_reload(id); + }); + for (auto id : selection) + if (auto spritesheet = spritesheet_get(document, id)) + { + document.spritesheet_hash_set_saved(id); + toast_log(Level::INFO, TOAST_RELOAD_SPRITESHEET, id, path::to_utf8(spritesheet->path)); + } + }); + }, + TOOLTIP_RELOAD_SPRITESHEETS); + actions.add( + ACTION_REPLACE, isOne, [&]() { dialog.file_open(Dialog::SPRITESHEET_REPLACE); }, TOOLTIP_REPLACE_SPRITESHEET); + actions.add( + ACTION_MERGE, [selection]() { return selection.size() > 1; }, + [&]() + { + spritesheets.mergeIds = selection; + spritesheets.mergePopup.open(); }); - }; - 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 = spritesheet_get(document, document.spritesheet.reference); - if (spritesheet && window.dialog) window_directory_open(*window.dialog, document, spritesheet->path); - }; - window.remove_unused = [](Window&, Manager&, Settings&, Document& document, Clipboard&) - { - auto unused = document.model.unused_get(ElementType::SPRITESHEET); - if (unused.empty()) return; - document.edit_apply(EDIT_REMOVE_UNUSED_SPRITESHEETS, - [&](model::Model& model) - { - std::erase_if(model.content.spritesheets, - [&](const model::Spritesheet& spritesheet) - { - if (!unused.contains(spritesheet.id)) return false; - toast_log(Level::INFO, TOAST_REMOVE_SPRITESHEET, spritesheet.id, - path::to_utf8(spritesheet.path)); - return true; - }); - }); - }; - window.reload = [](Window&, Manager&, Settings&, Document& document, Clipboard&) - { - auto selected = document.spritesheet.selection; - document.edit_apply(EDIT_RELOAD_SPRITESHEETS, - [&](model::Model&) - { - for (auto id : selected) - document.texture_reload(id); - }); - for (auto id : selected) - if (auto spritesheet = spritesheet_get(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)) + actions.add( + ACTION_PACK, [&]() { return selection.size() == 1 && is_spritesheet_regions(document, *selection.begin()); }, + [&]() + { + spritesheets.packId = *selection.begin(); + spritesheets.packPopup.open(); + }, + TOOLTIP_PACK_SPRITESHEET); + actions.add( + ACTION_SAVE, isAny, + [&]() + { + if (!settings.fileIsWarnOverwrite) + return command_push(panel, [selection](Document& document) { spritesheets_save(document, selection); }); + spritesheets.saveIds = selection; + spritesheets.overwritePopup.open(); + }, + TOOLTIP_SAVE_SPRITESHEETS); + items_clipboard_actions_add(actions, panel, SelectionKind::SPRITESHEETS, + EDIT_PASTE_SPRITESHEETS, TOAST_DESERIALIZE_SPRITESHEETS_FAILED, + spritesheets_get); + + auto image_get = [&](int id) { - 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(); - } + auto texture = document.texture_get(id); + auto isValid = texture && texture->is_valid(); + auto& image = isValid ? *texture : resources.icons[icon::NONE]; + return CardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}; + }; + ListRows rows{ + .label_get = + [&](int id) + { + auto pathString = path::to_utf8(spritesheet_get(document, id)->path); + auto label = std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(id, pathString)); + return document.spritesheet_is_dirty(id) + ? std::vformat(localize.get(FORMAT_SPRITESHEET_NOT_SAVED), std::make_format_args(label)) + : label; + }, + .tooltip_draw = + [&](int id) + { + auto image = image_get(id); + tooltip_image_draw(image, + [&]() + { + tooltip_name_draw(resources, path::to_utf8(spritesheet_get(document, id)->path)); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); + if (image.isValid) + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_TEXTURE_SIZE), + std::make_format_args(image.texture->size.x, image.texture->size.y)) + .c_str()); + else + ImGui::TextUnformatted(localize.get(TOOLTIP_SPRITESHEET_INVALID)); + ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); + }); + }, + .image_get = image_get, + .select = + [&](int) + { + document.editTarget = Document::EditTarget::SPRITESHEET; + document.selected_clear(SelectionKind::REGIONS); + }, + .activate = open, + .cardLines = SPRITESHEET_CARD_LINES}; + list_panel_draw(panel, actions, + {{ACTION_ADD, ACTION_RELOAD, ACTION_REPLACE}, {ACTION_REMOVE_UNUSED, ACTION_SAVE}}, + [&]() { content_list_draw(panel, SelectionKind::SPRITESHEETS, item_ids_get(items), rows); }); + } + ImGui::End(); - 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, - [&]() - { - 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, [&]() { 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; + spritesheets_merge_popup_update(panel, spritesheets); + spritesheets_pack_popup_update(panel, spritesheets); + spritesheets_overwrite_popup_update(panel, spritesheets); } } diff --git a/src/imgui/window/timeline/context.hpp b/src/imgui/window/timeline/context.hpp index ca2da65..ede1bbe 100644 --- a/src/imgui/window/timeline/context.hpp +++ b/src/imgui/window/timeline/context.hpp @@ -25,7 +25,7 @@ #include "model/frames.hpp" #include "vector.hpp" -#include "window/window.hpp" +#include "window/panel.hpp" using namespace anm2ed::resource; using namespace anm2ed::types; @@ -164,7 +164,6 @@ namespace anm2ed::imgui model::Model& model; Playback& playback; Reference reference; - Storage& region; const model::Animation* animation{}; float rowFrameChildHeight{}; bool isLightTheme{}; diff --git a/src/imgui/window/timeline/frames.cpp b/src/imgui/window/timeline/frames.cpp index e2cee50..24aaadf 100644 --- a/src/imgui/window/timeline/frames.cpp +++ b/src/imgui/window/timeline/frames.cpp @@ -39,7 +39,7 @@ namespace anm2ed::imgui frames_select_for(document, uids); if (targetType == LAYER) if (auto layer = model::item_get(document.model.content.layers, targetID)) - document.spritesheet.reference = layer->spritesheetId; + document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); }); } @@ -409,7 +409,7 @@ namespace anm2ed::imgui { if (type == LAYER) if (auto layer = model::item_get(model.content.layers, id)) - document.spritesheet.reference = layer->spritesheetId; + document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); if (type != TRIGGER) { @@ -454,8 +454,7 @@ namespace anm2ed::imgui } reference_set(frameReference); isReferenced = true; - region.reference = -1; - region.selection.clear(); + document.selected_clear(SelectionKind::REGIONS); } ImGui::PopStyleVar(); diff --git a/src/imgui/window/timeline/menus.cpp b/src/imgui/window/timeline/menus.cpp index 629284f..1ebca90 100644 --- a/src/imgui/window/timeline/menus.cpp +++ b/src/imgui/window/timeline/menus.cpp @@ -74,7 +74,7 @@ namespace anm2ed::imgui model::Region region{.crop = frame->crop, .size = frame->size, .pivot = frame->pivot}; - document.spritesheet.reference = spritesheetID; + document.focused_id_set(SelectionKind::SPRITESHEETS, spritesheetID); settingsPtr->windowIsRegions = true; manager.makeRegionSpritesheetId = spritesheetID; manager.makeRegion = region; @@ -196,7 +196,7 @@ namespace anm2ed::imgui } ImGui::EndChild(); - auto result = window_popup_buttons_draw(manager, localize.get(BASIC_CONFIRM)); + auto result = popup_buttons_draw(manager, localize.get(BASIC_CONFIRM)); if (result == PopupButton::CONFIRM) { auto targetName = groupName; diff --git a/src/imgui/window/timeline/popups.cpp b/src/imgui/window/timeline/popups.cpp index 0c3777d..97e0d55 100644 --- a/src/imgui/window/timeline/popups.cpp +++ b/src/imgui/window/timeline/popups.cpp @@ -31,7 +31,7 @@ namespace anm2ed::imgui input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat); ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isMakeManyRegionsMapFrames); - auto result = window_popup_buttons_draw(manager, localize.get(LABEL_MAKE_MANY_REGIONS)); + auto result = popup_buttons_draw(manager, localize.get(LABEL_MAKE_MANY_REGIONS)); if (result == PopupButton::CONFIRM) edit_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, [targetFrames = makeManyRegionReferences, format = settings.generateRegionNameFormat, diff --git a/src/imgui/window/timeline/selection.cpp b/src/imgui/window/timeline/selection.cpp index 13117be..1111871 100644 --- a/src/imgui/window/timeline/selection.cpp +++ b/src/imgui/window/timeline/selection.cpp @@ -215,7 +215,7 @@ namespace anm2ed::imgui { if (itemReference.itemType == LAYER) if (auto layer = model::item_get(targetDocument.model.content.layers, itemReference.itemID)) - targetDocument.spritesheet.reference = layer->spritesheetId; + targetDocument.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); reference_set_item_reference_for(targetDocument, itemReference); } @@ -392,7 +392,7 @@ namespace anm2ed::imgui { if (row.type == LAYER) if (auto layer = model::item_get(model.content.layers, row.id)) - document.spritesheet.reference = layer->spritesheetId; + document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); reference_set(row_item_reference_get(rowReference)); } frames_selection_reset_for(document); diff --git a/src/imgui/window/timeline/timeline.cpp b/src/imgui/window/timeline/timeline.cpp index d00d2d9..2b58de5 100644 --- a/src/imgui/window/timeline/timeline.cpp +++ b/src/imgui/window/timeline/timeline.cpp @@ -9,7 +9,7 @@ namespace anm2ed::imgui Clipboard& clipboard) : TimelineState(std::move(state)), manager(manager), settings(settings), resources(resources), clipboard(clipboard), document(*manager.get()), model(document.model), playback(document.playback), - reference(document.reference_get()), region(document.region) + reference(document.reference_get()) { } diff --git a/src/imgui/window/window.cpp b/src/imgui/window/window.cpp deleted file mode 100644 index a340502..0000000 --- a/src/imgui/window/window.cpp +++ /dev/null @@ -1,578 +0,0 @@ -#include "window.hpp" - -#include -#include -#include - -#include "actions.hpp" -#include "path.hpp" -#include "strings.hpp" -#include "toast.hpp" -#include "util/imgui/layout.hpp" -#include "util/imgui/shortcut.hpp" - -using namespace anm2ed::resource; -using namespace anm2ed::types; -using namespace anm2ed::util; -using namespace glm; - -namespace anm2ed::imgui -{ - 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; } - - void window_command_push(Window& window, Manager& manager, Settings& settings, Clipboard& clipboard, - const Window::Command& command) - { - if (!command) return; - manager.command_push({manager.selected, - [&window, &settings, &clipboard, command](Manager& manager, Document& document) mutable - { command(window, manager, settings, document, clipboard); }}); - } - - void window_rename_finish(Window& window, Manager& manager, int key, const std::string& name) - { - manager.command_push({manager.selected, [&window, key, name](Manager&, Document& document) - { - if (!window.rename_apply || window.name_get(document, key) == name) return; - document.edit_apply(window.renameEdit, [&](model::Model& model) - { window.rename_apply(document, model, key, name); }); - }}); - } - - void window_copy(Window& window, Document& document, Clipboard& clipboard) - { - std::string clipboardText{}; - for (auto key : window.storage_get(document).selection) - clipboardText += window.copy_get(document, key); - if (!clipboardText.empty()) clipboard.set(clipboardText); - } - - void window_paste(Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) - { - if (clipboard.is_empty() || !window.paste_apply) return; - std::string errorString{}; - auto key = -1; - document.edit_apply(window.pasteEdit, [&](model::Model& model) - { key = window.paste_apply(document, model, clipboard.get(), &errorString); }); - if (key == -1) - { - if (!errorString.empty()) toast_log(Level::ERROR, window.deserializeFailedToast, errorString); - return; - } - auto& storage = window.storage_get(document); - window.newElementId = key; - storage.selection = {key}; - storage.reference = key; - if (window.row_select) window.row_select(window, document, key); - } - - void window_remove_unused(Window& window, Manager&, Settings&, Document& document, Clipboard&) - { - if (!window.unused_remove) return; - document.edit_apply(window.removeUnusedEdit, [&](model::Model& model) { window.unused_remove(document, model); }); - } - - bool is_window_group_selected(const Window& window) - { - return window.elementType == ElementType::ANIMATION && !window.selection.empty(); - } - - bool is_window_item_selected(Window& window, Document& document) - { - return !window.storage_get(document).selection.empty() || is_window_group_selected(window); - } - - void window_properties(Window& window, Manager& manager, Settings& settings, Clipboard& clipboard, int id) - { - 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; - 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, int key) - { - 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, key); - ImGui::EndTooltip(); - } - ImGui::PopStyleVar(2); - } - - bool window_row_draw(Window& window, Manager& manager, Resources& resources, Document& document, 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, key) - : isReferenced ? resource::font::ITALICS - : resource::font::REGULAR; - auto isFontPushed = font != resource::font::REGULAR; - auto name = window.name_get ? window.name_get(document, key) : std::string{}; - auto label = window.row_label_get ? window.row_label_get(document, key) : 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 : name, isSelected, - ImGuiSelectableFlags_None, window.renameState); - if (isActivated && window.renameState == RENAME_BEGIN) - { - window.renameId = key; - window.renameText = name; - } - else if (isActivated && window.renameState == RENAME_FINISHED) - { - if (isRenaming) window_rename_finish(window, manager, key, 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, key, index); - window_tooltip_update(window, resources, document, key); - 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(resource::texture::id_get(*image.texture), 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) - { - auto& storage = window.storage_get(document); - auto cardSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * window.cardLines); - auto style = ImGui::GetStyle(); - - window.order = window.keys_get(document); - - 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]; - - 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, id); - auto tint = image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID; - auto label = window.row_label_get ? window.row_label_get(document, id) : window.name_get(document, id); - - 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, id); - } - - isBreak = window.row_drag_drop_update && window.row_drag_drop_update(window, manager, document, id, 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(resource::texture::id_get(*image.texture), 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) - { - window.order = window.keys_get(document); - auto arrowSelectionId = window_selection_start(window, document, window.order); - for (int i = 0; i < (int)window.order.size(); ++i) - if (window_row_draw(window, manager, resources, document, 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) - { - 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) - { - if (path.empty()) return; - std::error_code ec{}; - auto absolutePath = std::filesystem::weakly_canonical(document.directory_get() / path, ec); - if (ec) absolutePath = document.directory_get() / path; - auto target = std::filesystem::is_directory(absolutePath) ? absolutePath - : std::filesystem::is_directory(absolutePath.parent_path()) ? absolutePath.parent_path() - : document.directory_get(); - dialog.file_explorer_open(target); - } - - PopupButton window_popup_buttons_draw(Manager& manager, const char* confirmLabel, bool isConfirmEnabled, - StringType cancelLabel) - { - auto widgetSize = widget_size_with_row_get(2); - auto result = PopupButton::NONE; - - ImGui::BeginDisabled(!isConfirmEnabled); - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(confirmLabel, widgetSize)) result = PopupButton::CONFIRM; - ImGui::EndDisabled(); - - ImGui::SameLine(); - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(cancelLabel), widgetSize)) result = PopupButton::CANCEL; - return result; - } - - void window_update(Window& window, Manager& manager, Settings& settings, Resources& resources, Dialog& dialog, - Clipboard& clipboard) - { - auto document = manager.get(); - if (!document || !window.isOpen || !window.storage_get) return; - window.dialog = &dialog; - - if (ImGui::Begin(localize.get(window.title), &(settings.*window.isOpen))) - { - if (window.is_available && !window.is_available(window, *document)) - { - if (window.unavailableText != STRING_UNDEFINED) ImGui::TextUnformatted(localize.get(window.unavailableText)); - } - else - { - auto childSize = size_without_footer_get((int)window.footer.size()); - auto style = ImGui::GetStyle(); - window.tooltipWindowPadding = style.WindowPadding; - window.tooltipItemSpacing = style.ItemSpacing; - - 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); - else if (isCards) - window_cards_draw(window, manager, settings, resources, clipboard, *document); - else - 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); - } - ImGui::EndChild(); - if (isCards) ImGui::PopStyleVar(); - - 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); - - window_footer_draw(window, manager, settings, *document, clipboard); - if (window.body_update) window.body_update(window, manager, settings, resources, clipboard, *document); - } - } - ImGui::End(); - - 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); - } -} diff --git a/src/imgui/window/window.hpp b/src/imgui/window/window.hpp deleted file mode 100644 index 926c76d..0000000 --- a/src/imgui/window/window.hpp +++ /dev/null @@ -1,282 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include "clipboard.hpp" -#include "dialog.hpp" -#include "manager.hpp" -#include "model/xml.hpp" -#include "resources.hpp" -#include "settings.hpp" -#include "storage.hpp" -#include "util/imgui/popup.hpp" -#include "util/imgui/selectable.hpp" - -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 - { -#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 - { - const resource::Image* 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 KeysGet = std::function(Document&)>; - using NameGet = std::function; - using RowFontGet = std::function; - using RowSelect = std::function; - using RenameApply = std::function; - using PasteApply = std::function; - using UnusedRemove = std::function; - using TooltipDraw = std::function; - using RowDragDropUpdate = std::function; - using CardImageGet = std::function; - using PropertiesOpen = std::function; - using Command = std::function; - using IsEnabled = std::function; - using Update = std::function; - - StringType title{}; - bool Settings::* isOpen{}; - ElementType elementType{ElementType::UNKNOWN}; - const char* childLabel{"##Window Child"}; - 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}; - RenameState renameState{RENAME_SELECTABLE}; - std::string renameText{}; - PopupHelper popup{STRING_UNDEFINED}; - PopupHelper popup2{STRING_UNDEFINED}; - PopupHelper popup3{STRING_UNDEFINED}; - std::set selection{}; - std::set selection2{}; - std::vector dragSelection{}; - std::vector order{}; - model::Region editRegion{}; - Dialog* dialog{}; - WindowFlags flags{WINDOW_COPY | WINDOW_PASTE}; - bool isPreserveEditElementOnOpen{}; - ImVec2 tooltipWindowPadding{}; - ImVec2 tooltipItemSpacing{}; - StorageGet storage_get{}; - KeysGet keys_get{}; - NameGet name_get{}; - NameGet row_label_get{}; - NameGet copy_get{}; - RowFontGet row_font_get{}; - RowSelect row_select{}; - RenameApply rename_apply{}; - PasteApply paste_apply{}; - UnusedRemove unused_remove{}; - TooltipDraw tooltip_draw{}; - RowDragDropUpdate row_drag_drop_update{}; - CardImageGet card_image_get{}; - PropertiesOpen properties_open{}; -#define X(symbol, action, command) Command command{}; - WINDOW_FLAGS -#undef X - Command merge_open{}; - std::map enabled{}; - IsEnabled is_available{}; - Update rows_update{}; - Update body_update{}; - Update popup_update{}; - Update post_update{}; - }; - - Window animations_window_register(); - Window regions_window_register(); - Window sounds_window_register(); - Window spritesheets_window_register(); - Window layers_window_register(); - 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(); - 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&, int, int, int); - void window_cards_draw(Window&, Manager&, Settings&, Resources&, Clipboard&, Document&); - 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); - - // Binds a window's generic list behavior (keys, names, copy/paste, remove unused) to a list of content items. - template - void window_items_bind(Window& window, std::function*(Document&, model::Model&)> items_get) - { - auto items_const_get = [items_get](Document& document) { return items_get(document, document.model); }; - window.keys_get = [items_const_get](Document& document) - { - std::vector keys{}; - if (auto items = items_const_get(document)) - for (const auto& item : *items) - keys.push_back(item.id); - return keys; - }; - window.copy_get = [items_const_get](Document& document, int key) - { - auto items = items_const_get(document); - auto item = items ? model::item_get(*items, key) : nullptr; - return item ? model::item_to_string(*item) : std::string{}; - }; - window.paste_apply = - [items_get](Document& document, model::Model& model, const std::string& text, std::string* errorString) - { - auto items = items_get(document, model); - auto pasted = model::items_from_string(text, errorString); - if (!items || pasted.empty()) return -1; - for (auto& item : pasted) - { - item.id = model::item_next_id_get(*items); - items->push_back(std::move(item)); - } - return items->back().id; - }; - if constexpr (requires(Item item) { item.name; }) - { - window.name_get = [items_const_get](Document& document, int key) - { - auto items = items_const_get(document); - auto item = items ? model::item_get(*items, key) : nullptr; - return item ? item->name : std::string{}; - }; - window.rename_apply = [items_get](Document& document, model::Model& model, int key, const std::string& name) - { - auto items = items_get(document, model); - if (auto item = items ? model::item_get(*items, key) : nullptr) item->name = name; - }; - } - window.unused_remove = [items_get, type = window.elementType](Document& document, model::Model& model) - { - auto unused = model.unused_get(type); - if (auto items = items_get(document, model)) - std::erase_if(*items, [&](const Item& item) { return unused.contains(item.id); }); - }; - } - - // Adds `edited` as a new item (reference -1) or replaces the item with that id, then selects it. - template - void window_item_apply_push(Window& window, Manager& manager, Item edited, int reference, - std::function*(Document&, model::Model&)> items_get, - int insertIndex = -1) - { - manager.command_push( - {manager.selected, [&window, edited, reference, items_get, insertIndex](Manager&, Document& document) - { - document.edit_apply(reference == -1 ? window.addEdit : window.propertiesEdit, - [&](model::Model& model) - { - auto items = items_get(document, model); - if (!items) return; - auto target = reference == -1 ? nullptr : model::item_get(*items, reference); - if (reference != -1 && !target) return; - auto changed = edited; - changed.id = reference == -1 ? model::item_next_id_get(*items) : reference; - if (target) - { - changed.uid = target->uid; - *target = changed; - } - else - { - changed.uid = util::uid_next(); - auto position = - insertIndex < 0 ? (int)items->size() : std::min(insertIndex, (int)items->size()); - items->insert(items->begin() + position, 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); - }); - }}); - } -} diff --git a/src/imgui/wizard/change_all_frame_properties.cpp b/src/imgui/wizard/change_all_frame_properties.cpp index c20dc26..951a62d 100644 --- a/src/imgui/wizard/change_all_frame_properties.cpp +++ b/src/imgui/wizard/change_all_frame_properties.cpp @@ -168,7 +168,7 @@ namespace anm2ed::imgui::wizard }; auto combo_draw = [&](const char* id, StringType label, bool& isEnabled, int& value, const std::vector& ids, - std::vector& labels) + const std::vector& labels) { ImGui::PushID(id); if (std::ranges::find(ids, value) == ids.end()) value = ids.front(); @@ -187,18 +187,16 @@ namespace anm2ed::imgui::wizard ImGui::PopID(); }; - std::vector noneIds{-1}; - std::string noneLabel = localize.get(BASIC_NONE); - std::vector noneLabels{noneLabel.c_str()}; std::vector interpolationIds{}; - std::vector interpolationLabels{}; + std::vector interpolationLabels{}; for (int i = 0; i < (int)std::size(INTERPOLATION_LABELS); ++i) { interpolationIds.push_back(i); interpolationLabels.push_back(localize.get(INTERPOLATION_LABELS[i])); } - auto regions = - document.layer_regions_get(document.reference_get().itemType == LAYER ? document.reference_get().itemID : -1); + auto regions = document.choices_get( + SelectionKind::REGIONS, document.reference_get().itemType == LAYER ? document.reference_get().itemID : -1); + auto shaders = document.choices_get(SelectionKind::SHADERS); if (!isLayerPropertyAvailable) regionId = shaderId = -1; ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImGui::GetStyle().ItemInnerSpacing); @@ -212,15 +210,12 @@ namespace anm2ed::imgui::wizard rows_draw(colorRows, true); ImGui::BeginDisabled(!isLayerPropertyAvailable); - combo_draw("Region", BASIC_REGION, settings.changeIsRegion, regionId, regions ? regions->ids : noneIds, - regions ? regions->labels : noneLabels); + combo_draw("Region", BASIC_REGION, settings.changeIsRegion, regionId, regions.ids, regions.labels); ImGui::EndDisabled(); combo_draw("Interpolation", BASIC_INTERPOLATED, settings.changeIsInterpolationSet, settings.changeInterpolation, interpolationIds, interpolationLabels); ImGui::BeginDisabled(!isLayerPropertyAvailable); - combo_draw("Shader", BASIC_SHADER, settings.changeIsShader, shaderId, - document.shader.ids.empty() ? noneIds : document.shader.ids, - document.shader.labels.empty() ? noneLabels : document.shader.labels); + combo_draw("Shader", BASIC_SHADER, settings.changeIsShader, shaderId, shaders.ids, shaders.labels); ImGui::EndDisabled(); bool_draw("Visible", BASIC_VISIBLE, settings.changeIsVisibleSet, settings.changeIsVisible); bool_draw("Flip X", LABEL_FLIP_X, settings.changeIsFlipXSet, settings.changeIsFlipX); diff --git a/src/manager.cpp b/src/manager.cpp index d735c19..135c796 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -262,10 +262,9 @@ namespace anm2ed auto layer = isLayer ? model::item_get(content.layers, id) : nullptr; auto null = isLayer ? nullptr : model::item_get(content.nulls, id); if (id != -1 && !layer && !null) return; - itemEdit = layer ? ItemEdit{layer->name, layer->spritesheetId, false} - : null ? ItemEdit{null->name, 0, null->isShowRect} + itemEdit = layer ? ItemEdit{id, layer->name, layer->spritesheetId, false} + : null ? ItemEdit{id, null->name, 0, null->isShowRect} : ItemEdit{}; - (isLayer ? document->layer : document->null).reference = id; itemPropertiesPopups[isLayer ? 0 : 1].open(); } diff --git a/src/manager.hpp b/src/manager.hpp index 9106061..764d2f4 100644 --- a/src/manager.hpp +++ b/src/manager.hpp @@ -64,6 +64,7 @@ namespace anm2ed struct ItemEdit { + int id{-1}; std::string name{}; int spritesheetId{}; bool isShowRect{}; diff --git a/src/selection.cpp b/src/selection.cpp index c180167..53f946f 100644 --- a/src/selection.cpp +++ b/src/selection.cpp @@ -39,12 +39,75 @@ namespace anm2ed selection.focus = model.handle_get(reference); } + // (id, uid) of every content item a kind selects from. + std::vector> content_keys_get(const Selection& selection, const model::Model& model, + SelectionKind kind) + { + std::vector> keys{}; + auto add = [&](const auto& items) + { + for (const auto& item : items) + keys.emplace_back(item.id, item.uid); + }; + auto& content = model.content; + if (kind == SelectionKind::SPRITESHEETS) add(content.spritesheets); + if (kind == SelectionKind::SHADERS) add(content.shaders); + if (kind == SelectionKind::LAYERS) add(content.layers); + if (kind == SelectionKind::NULLS) add(content.nulls); + if (kind == SelectionKind::EVENTS) add(content.events); + if (kind == SelectionKind::SOUNDS) add(content.sounds); + if (kind == SelectionKind::REGIONS) + if (auto spritesheet = model::item_get(content.spritesheets, + selection_focus_id_get(selection, model, SelectionKind::SPRITESHEETS))) + add(spritesheet->regions); + return keys; + } + + std::set selection_ids_get(const Selection& selection, const model::Model& model, SelectionKind kind) + { + std::set ids{}; + auto uids = selection.uids.find(kind); + if (uids == selection.uids.end()) return ids; + for (auto [id, uid] : content_keys_get(selection, model, kind)) + if (uids->second.contains(uid)) ids.insert(id); + return ids; + } + + void selection_ids_set(Selection& selection, const model::Model& model, SelectionKind kind, const std::set& ids) + { + auto& uids = selection.uids[kind]; + uids.clear(); + for (auto [id, uid] : content_keys_get(selection, model, kind)) + if (ids.contains(id)) uids.insert(uid); + } + + int selection_focus_id_get(const Selection& selection, const model::Model& model, SelectionKind kind) + { + auto focus = selection.focuses.find(kind); + if (focus == selection.focuses.end()) return -1; + for (auto [id, uid] : content_keys_get(selection, model, kind)) + if (uid == focus->second) return id; + return -1; + } + + void selection_focus_id_set(Selection& selection, const model::Model& model, SelectionKind kind, int id) + { + selection.focuses.erase(kind); + for (auto [itemId, uid] : content_keys_get(selection, model, kind)) + if (itemId == id) + { + selection.focuses[kind] = uid; + return; + } + } + // After an edit: drops uids that no longer exist, and moves a focus whose element was removed to its nearest // survivor (a frame at the same index of its track, the animation's root track, or the nearest animation). void selection_follow(Selection& selection, const model::Model& model, const model::UidIndex& index, Reference before) { for (auto& [kind, uids] : selection.uids) - std::erase_if(uids, [&](std::uint64_t uid) { return !index.contains(uid); }); + if (kind < SelectionKind::SPRITESHEETS) + std::erase_if(uids, [&](std::uint64_t uid) { return !index.contains(uid); }); auto [animationUid, itemUid, frameUid] = selection.focus; auto is_removed = [&](std::uint64_t uid) { return uid && !index.contains(uid); }; diff --git a/src/selection.hpp b/src/selection.hpp index b7b4e35..e8829bb 100644 --- a/src/selection.hpp +++ b/src/selection.hpp @@ -13,7 +13,14 @@ namespace anm2ed ANIMATION_GROUPS, TRACKS, GROUPS, - FRAMES + FRAMES, + SPRITESHEETS, + REGIONS, + SHADERS, + LAYERS, + NULLS, + EVENTS, + SOUNDS }; // What is selected, by element uid, plus the focused animation/track/frame. uids follow elements through edits, @@ -22,6 +29,7 @@ namespace anm2ed { std::map> uids{}; Handle focus{}; + std::map focuses{}; bool operator==(const Selection&) const = default; }; @@ -30,5 +38,11 @@ namespace anm2ed void selection_references_set(Selection&, const model::Model&, SelectionKind, const std::set&); Reference selection_focus_get(const Selection&, const model::UidIndex&); void selection_focus_set(Selection&, const model::Model&, Reference); + // Content items (spritesheets, regions of the focused spritesheet, shaders, layers, ...) are selected by uid and + // read back as ids. + std::set selection_ids_get(const Selection&, const model::Model&, SelectionKind); + void selection_ids_set(Selection&, const model::Model&, SelectionKind, const std::set&); + int selection_focus_id_get(const Selection&, const model::Model&, SelectionKind); + void selection_focus_id_set(Selection&, const model::Model&, SelectionKind, int); void selection_follow(Selection&, const model::Model&, const model::UidIndex&, Reference); } diff --git a/src/snapshots.cpp b/src/snapshots.cpp index 5b389fb..689153b 100644 --- a/src/snapshots.cpp +++ b/src/snapshots.cpp @@ -16,14 +16,6 @@ namespace anm2ed::snapshots return left.time == right.time && left.isPlaying == right.isPlaying && left.isFinished == right.isFinished; } - bool is_value_equal(const Storage& left, const Storage& right) - { - return left.reference == right.reference && left.hovered == right.hovered && - left.labelsString == right.labelsString && left.ids == right.ids && - static_cast&>(left.selection) == static_cast&>(right.selection) && - left.references == right.references; - } - bool is_step_empty(const SnapshotStep& step) { #define X(type, name) \ diff --git a/src/snapshots.hpp b/src/snapshots.hpp index 2dd1c67..eb3a7c1 100644 --- a/src/snapshots.hpp +++ b/src/snapshots.hpp @@ -8,7 +8,6 @@ #include "model/model.hpp" #include "playback.hpp" #include "selection.hpp" -#include "storage.hpp" namespace anm2ed::snapshots { @@ -23,14 +22,6 @@ namespace anm2ed #define SNAPSHOT_STEP_STATE_FIELDS \ X(model::Model, model) \ X(Playback, playback) \ - X(Storage, event) \ - X(Storage, layer) \ - X(Storage, merge) \ - X(Storage, null) \ - X(Storage, region) \ - X(Storage, shader) \ - X(Storage, sound) \ - X(Storage, spritesheet) \ X(Selection, selection) \ X(float, frameTime) \ X(AssetKeys, textures) \ diff --git a/src/storage.cpp b/src/storage.cpp deleted file mode 100644 index 98e1a81..0000000 --- a/src/storage.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "storage.hpp" - -#include - -namespace anm2ed -{ - void Storage::clear() { *this = Storage(); } - - void Storage::labels_set(std::vector labels) { labels_set(std::move(labels), {}); } - - void Storage::labels_set(std::vector labels, std::vector ids) - { - labelsString = std::move(labels); - this->ids = std::move(ids); - this->labels.clear(); - for (auto& label : labelsString) - this->labels.emplace_back(label.c_str()); - } -} diff --git a/src/storage.hpp b/src/storage.hpp deleted file mode 100644 index 7cea83b..0000000 --- a/src/storage.hpp +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "model/common.hpp" -#include "util/imgui/multiselect.hpp" - -namespace anm2ed -{ - class Storage - { - public: - int reference{-1}; - int hovered{-1}; - std::vector labelsString{}; - std::vector labels{}; - std::vector ids{}; - imgui::MultiSelectStorage selection{}; - std::set references{}; - - void clear(); - void labels_set(std::vector); - void labels_set(std::vector, std::vector); - }; -} diff --git a/src/util/imgui/input.cpp b/src/util/imgui/input.cpp index c66c810..f999cea 100644 --- a/src/util/imgui/input.cpp +++ b/src/util/imgui/input.cpp @@ -1,8 +1,8 @@ #include "input.hpp" #include -#include #include +#include #include @@ -51,8 +51,12 @@ namespace anm2ed::imgui return isActivated; } - bool combo_id_mapped(const std::string& label, int* id, const std::vector& ids, std::vector& labels) + bool combo_id_mapped(const std::string& label, int* id, const std::vector& ids, + const std::vector& labelStrings) { + std::vector labels{}; + for (const auto& labelString : labelStrings) + labels.push_back(labelString.c_str()); if (!id) return false; int index = -1; @@ -75,7 +79,7 @@ namespace anm2ed::imgui } edit_state::Type drag_int_persistent(const char* label, int* value, float speed, int min, int max, const char* format, - ImGuiSliderFlags flags) + ImGuiSliderFlags flags) { static bool isEditing{}; static int start{INT_MAX}; @@ -106,7 +110,7 @@ namespace anm2ed::imgui } edit_state::Type drag_float_persistent(const char* label, float* value, float speed, float min, float max, - const char* format, ImGuiSliderFlags flags) + const char* format, ImGuiSliderFlags flags) { static bool isEditing{}; static float start{NAN}; @@ -137,7 +141,7 @@ namespace anm2ed::imgui } edit_state::Type drag_float2_persistent(const char* label, vec2* value, float speed, float min, float max, - const char* format, ImGuiSliderFlags flags) + const char* format, ImGuiSliderFlags flags) { static bool isEditing{}; static vec2 start{NAN}; @@ -232,8 +236,7 @@ namespace anm2ed::imgui bool isSelected = value && *value == buttonValue; if (isSelected) ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive)); - bool isActivated = - ImGui::ImageButton(label, texture, size, ImVec2(0, 0), ImVec2(1, 1), ImVec4(0, 0, 0, 0), tint); + bool isActivated = ImGui::ImageButton(label, texture, size, ImVec2(0, 0), ImVec2(1, 1), ImVec4(0, 0, 0, 0), tint); if (isSelected) ImGui::PopStyleColor(); if (isActivated && value) *value = buttonValue; diff --git a/src/util/imgui/input.hpp b/src/util/imgui/input.hpp index 781b044..4884c99 100644 --- a/src/util/imgui/input.hpp +++ b/src/util/imgui/input.hpp @@ -19,15 +19,15 @@ namespace anm2ed::imgui bool input_int2_range(const char*, glm::ivec2&, glm::ivec2, glm::ivec2, ImGuiInputTextFlags = 0); bool input_float_range(const char*, float&, float, float, float = STEP, float = STEP_FAST, const char* = "%.3f", ImGuiInputTextFlags = 0); - types::edit_state::Type drag_int_persistent(const char*, int*, float = DRAG_SPEED, int = {}, int = {}, const char* = "%d", - ImGuiSliderFlags = 0); + types::edit_state::Type drag_int_persistent(const char*, int*, float = DRAG_SPEED, int = {}, int = {}, + const char* = "%d", ImGuiSliderFlags = 0); types::edit_state::Type drag_float_persistent(const char*, float*, float = DRAG_SPEED, float = {}, float = {}, - const char* = "%.3f", ImGuiSliderFlags = 0); + const char* = "%.3f", ImGuiSliderFlags = 0); types::edit_state::Type drag_float2_persistent(const char*, glm::vec2*, float = DRAG_SPEED, float = {}, float = {}, - const char* = "%.3f", ImGuiSliderFlags = 0); + const char* = "%.3f", ImGuiSliderFlags = 0); types::edit_state::Type color_edit3_persistent(const char*, glm::vec3*, ImGuiColorEditFlags = 0); types::edit_state::Type color_edit4_persistent(const char*, glm::vec4*, ImGuiColorEditFlags = 0); bool radio_button_icon(const char*, int*, int, ImTextureID, ImVec2, ImVec4 = ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); bool combo_negative_one_indexed(const std::string&, int*, std::vector&); - bool combo_id_mapped(const std::string&, int*, const std::vector&, std::vector&); + bool combo_id_mapped(const std::string&, int*, const std::vector&, const std::vector&); } diff --git a/tests/selection.cpp b/tests/selection.cpp index bea624e..9977c2d 100644 --- a/tests/selection.cpp +++ b/tests/selection.cpp @@ -90,3 +90,26 @@ TEST_CASE("track and group selection follow regrouping") CHECK(selection_references_get(selection, index, SelectionKind::TRACKS) == std::set{{0, LAYER, 0}}); CHECK(selection_references_get(selection, index, SelectionKind::GROUPS) == std::set{{0, LAYER, groupId}}); } + +TEST_CASE("content selection follows items, and regions follow the focused spritesheet") +{ + auto anm2 = fixture_load_with_uids("05_regions.anm2"); + Selection selection{}; + auto& regions = model::item_get(anm2.content.spritesheets, 0)->regions; + REQUIRE(regions.size() > 1); + auto regionId = regions[1].id; + + selection_ids_set(selection, anm2, SelectionKind::REGIONS, {regionId}); + CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty()); + + selection_focus_id_set(selection, anm2, SelectionKind::SPRITESHEETS, 0); + selection_ids_set(selection, anm2, SelectionKind::REGIONS, {regionId}); + selection_focus_id_set(selection, anm2, SelectionKind::REGIONS, regionId); + regions.erase(regions.begin()); + CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS) == std::set{regionId}); + CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == regionId); + + std::erase_if(regions, [&](const model::Region& region) { return region.id == regionId; }); + CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty()); + CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == -1); +}