From d2c0e32ff55d99df9bc51bdb1acd360c818c53a9 Mon Sep 17 00:00:00 2001 From: shweet Date: Sun, 22 Nov 2026 17:40:24 -0500 Subject: [PATCH] Start the editor from main, and hand paths over with a small instance listener Loader and State are folded into main.cpp. SDL_main gives Windows UTF-8 arguments. instance.cpp replaces the Socket class. A later editor sends its paths and waits for the first to answer. When something else holds the port, the editor now runs on its own instead of quietly exiting. --- src/instance.cpp | 133 ++++++++++++ src/instance.h | 16 ++ src/loader.cpp | 340 ----------------------------- src/loader.h | 30 --- src/main.cpp | 460 +++++++++++++++++++++++++++++++++------- src/socket.cpp | 275 ------------------------ src/socket.h | 60 ------ src/state.cpp | 269 ----------------------- src/state.h | 38 ---- tests/render/render.cpp | 22 ++ 10 files changed, 558 insertions(+), 1085 deletions(-) create mode 100644 src/instance.cpp create mode 100644 src/instance.h delete mode 100644 src/loader.cpp delete mode 100644 src/loader.h delete mode 100644 src/socket.cpp delete mode 100644 src/socket.h delete mode 100644 src/state.cpp delete mode 100644 src/state.h diff --git a/src/instance.cpp b/src/instance.cpp new file mode 100644 index 0000000..4fcd3c0 --- /dev/null +++ b/src/instance.cpp @@ -0,0 +1,133 @@ +#include "instance.h" + +#include +#include +#include + +#ifdef _WIN32 +#include +#include +using Handle = SOCKET; +constexpr Handle HANDLE_INVALID = INVALID_SOCKET; +constexpr auto SOCKET_REUSE = SO_EXCLUSIVEADDRUSE; +#else +#include +#include +#include +#include +using Handle = int; +constexpr Handle HANDLE_INVALID = -1; +constexpr auto SOCKET_REUSE = SO_REUSEADDR; +#define closesocket close +#endif + +constexpr auto INSTANCE_ADDRESS = "127.0.0.1"; +constexpr auto INSTANCE_PORT = 11414; +// The listening editor's answer once it has every path, telling a later one it was heard. +constexpr char INSTANCE_ANSWER[] = "anm2ed"; +constexpr int ANSWER_TIMEOUT_MS = 1000; +constexpr int BUFFER_SIZE = 4096; + +static Handle listener = HANDLE_INVALID; +static std::thread listenThread; +static std::atomic isListening = false; + +static sockaddr_in address_get() +{ + sockaddr_in address = {}; + address.sin_family = AF_INET; + address.sin_port = htons(INSTANCE_PORT); + inet_pton(AF_INET, INSTANCE_ADDRESS, &address.sin_addr); + return address; +} + +// Sends each path followed by a zero, then waits for the answer. +static bool paths_send(const std::vector& paths) +{ + auto handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + auto address = address_get(); + if (handle == HANDLE_INVALID) + return false; + if (connect(handle, (sockaddr*)&address, sizeof(address)) != 0) + { + closesocket(handle); + return false; + } + + std::string message; + for (auto& path : paths) + message += path + '\0'; + auto isSent = send(handle, message.data(), (int)message.size(), 0) == (int)message.size(); +#ifdef _WIN32 + DWORD timeout = ANSWER_TIMEOUT_MS; + shutdown(handle, SD_SEND); +#else + timeval timeout = {ANSWER_TIMEOUT_MS / 1000, ANSWER_TIMEOUT_MS % 1000 * 1000}; + shutdown(handle, SHUT_WR); +#endif + setsockopt(handle, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); + char answer[sizeof(INSTANCE_ANSWER)] = {}; + auto isAnswered = isSent && recv(handle, answer, sizeof(answer), MSG_WAITALL) == sizeof(answer) && + std::string_view(answer, sizeof(answer)) == std::string_view(INSTANCE_ANSWER, sizeof(answer)); + closesocket(handle); + return isAnswered; +} + +static void paths_receive(Handle client) +{ + std::string message; + char buffer[BUFFER_SIZE]; + for (int count = 0; (count = recv(client, buffer, sizeof(buffer), 0)) > 0;) + message.append(buffer, count); + send(client, INSTANCE_ANSWER, sizeof(INSTANCE_ANSWER), 0); + closesocket(client); + + for (std::size_t start = 0, end = 0; (end = message.find('\0', start)) != std::string::npos; start = end + 1) + { + if (end == start) + continue; + SDL_Event event = {}; + event.type = SDL_EVENT_USER; + event.user.data1 = SDL_strdup(message.substr(start, end - start).c_str()); + SDL_PushEvent(&event); + } +} + +InstanceRole instance_start(const std::vector& paths) +{ +#ifdef _WIN32 + WSADATA data = {}; + WSAStartup(MAKEWORD(2, 2), &data); +#endif + auto handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + auto address = address_get(); + int isReused = 1; + setsockopt(handle, SOL_SOCKET, SOCKET_REUSE, (const char*)&isReused, sizeof(isReused)); + if (handle == HANDLE_INVALID || bind(handle, (sockaddr*)&address, sizeof(address)) != 0 || + listen(handle, SOMAXCONN) != 0) + { + if (handle != HANDLE_INVALID) + closesocket(handle); + return paths_send(paths) ? INSTANCE_FORWARDED : INSTANCE_ALONE; + } + + listener = handle; + isListening = true; + listenThread = std::thread([] { + while (isListening) + if (auto client = accept(listener, nullptr, nullptr); client != HANDLE_INVALID) + paths_receive(client); + }); + return INSTANCE_FIRST; +} + +// Wakes the listening thread with an empty hand-off so it can see it should stop. +void instance_stop() +{ + if (!isListening) + return; + isListening = false; + paths_send({}); + listenThread.join(); + closesocket(listener); +} diff --git a/src/instance.h b/src/instance.h new file mode 100644 index 0000000..ece9696 --- /dev/null +++ b/src/instance.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +enum InstanceRole +{ + INSTANCE_FIRST, + INSTANCE_FORWARDED, + INSTANCE_ALONE +}; + +// One editor at a time. The first listens on a local port and pushes an SDL_EVENT_USER (data1, an SDL_strdup'd path) +// for each path a later one hands it, and that later one exits. When something else holds the port, it runs alone. +InstanceRole instance_start(const std::vector& paths); +void instance_stop(); diff --git a/src/loader.cpp b/src/loader.cpp deleted file mode 100644 index 9a217db..0000000 --- a/src/loader.cpp +++ /dev/null @@ -1,340 +0,0 @@ -#include "loader.h" - -#include -#include -#include -#include - -#include -#include - - -#include "log.h" -#include "sdl.h" -#include "texture.h" - -#include "snapshots.h" -#include "socket.h" - -#include "ui/theme.h" -#include "math_util.h" - -#ifdef _WIN32 -#include -#endif - -constexpr auto WINDOW_4K_SIZE = glm::ivec2(3840, 2160); -constexpr auto UI_SCALE_4K_DEFAULT = 150.0f; -constexpr auto WINDOW_DEFAULT_SIZE_MULTIPLIER = 0.90f; - -constexpr auto SOCKET_ADDRESS = "127.0.0.1"; -constexpr auto SOCKET_PORT = 11414; -constexpr uint32_t SOCKET_MAX_PATHS = 128; -constexpr uint32_t SOCKET_MAX_PATH_LENGTH = 32768; - -#ifdef _WIN32 -constexpr int SOCKET_ERROR_ADDRESS_IN_USE = WSAEADDRINUSE; -#else -constexpr int SOCKET_ERROR_ADDRESS_IN_USE = EADDRINUSE; -#endif - -static bool socket_paths_send(Socket& socket, const std::vector& paths) -{ - uint32_t count = htonl(static_cast(paths.size())); - if (!socket.send(&count, sizeof(count))) - return false; - - for (auto& path : paths) - { - uint32_t length = htonl(static_cast(path.size())); - if (!socket.send(&length, sizeof(length))) - return false; - if (!path.empty() && !socket.send(path.data(), path.size())) - return false; - } - - return true; -} - -static std::vector socket_paths_receive(Socket& socket) -{ - uint32_t count = 0; - if (!socket.receive(&count, sizeof(count))) - return {}; - count = ntohl(count); - if (count > SOCKET_MAX_PATHS) - return {}; - - std::vector paths; - paths.reserve(count); - - for (uint32_t i = 0; i < count; ++i) - { - uint32_t length = 0; - if (!socket.receive(&length, sizeof(length))) - return {}; - length = ntohl(length); - if (length > SOCKET_MAX_PATH_LENGTH) - return {}; - - std::string path(length, '\0'); - if (length > 0 && !socket.receive(path.data(), length)) - return {}; - paths.emplace_back(std::move(path)); - } - - return paths; -} - -std::filesystem::path Loader::settings_path() -{ - return preferences_directory_get() / "settings.ini"; -} - -Loader::Loader(int argc, const char** argv) -{ - for (int i = 1; i < argc; i++) - arguments.emplace_back(argv[i]); - - Socket testSocket; - if (!testSocket.open(SERVER)) - logger.warning(std::format("Failed to open socket; single instancing will not work.")); - - if (testSocket.bind({SOCKET_ADDRESS, SOCKET_PORT})) - { - socket = std::move(testSocket); - - if (!socket.listen()) - logger.warning("Could not listen on socket; single instancing disabled."); - else - { - isSocketThread = true; - logger.info(std::format("Opened socket at {}:{}", SOCKET_ADDRESS, SOCKET_PORT)); - } - } - else - { - if (testSocket.last_error() != SOCKET_ERROR_ADDRESS_IN_USE) - { - logger.fatal(std::format("Failed to bind single-instance socket (error {}).", testSocket.last_error())); - isError = true; - return; - } - - logger.info(std::format("Existing instance of program exists; passing arguments...")); - Socket clientSocket; - if (!clientSocket.open(CLIENT)) - logger.warning("Could not open client socket to forward arguments."); - else if (!clientSocket.connect({SOCKET_ADDRESS, SOCKET_PORT})) - logger.warning("Could not connect to existing instance."); - else if (!socket_paths_send(clientSocket, arguments)) - logger.warning("Failed to transfer arguments to existing instance."); - else - logger.info("Sent arguments to existing instance. Exiting."); - - isError = true; - return; - } - - settings = Settings(settings_path()); - SnapshotStack::max_size_set(settings.fileSnapshotStackSize); - localize.language = (Language)settings.language; - - if (!SDL_Init(SDL_INIT_VIDEO)) - { - logger.fatal(std::format("Could not initialize SDL! {}", SDL_GetError())); - isError = true; - return; - } - - logger.info("Initialized SDL"); - - auto windowProperties = SDL_CreateProperties(); - - if (windowProperties == 0) - { - logger.fatal(std::format("Could not initialize window properties! {}", SDL_GetError())); - isError = true; - return; - } - - if (settings.isDefault) - { - if (auto display = SDL_GetPrimaryDisplay(); display != 0) - { - if (auto mode = SDL_GetCurrentDisplayMode(display)) - { - if (mode->w >= WINDOW_4K_SIZE.x || mode->h >= WINDOW_4K_SIZE.y) - settings.uiScale = UI_SCALE_4K_DEFAULT; - settings.windowSize.x = mode->w * WINDOW_DEFAULT_SIZE_MULTIPLIER; - settings.windowSize.y = mode->h * WINDOW_DEFAULT_SIZE_MULTIPLIER; - } - else - logger.warning(std::format("Failed to query primary display mode: {}", SDL_GetError())); - } - else - logger.warning("Failed to detect primary display for UI scaling."); - } - - - SDL_SetStringProperty(windowProperties, SDL_PROP_WINDOW_CREATE_TITLE_STRING, "Anm2Ed"); - SDL_SetNumberProperty(windowProperties, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, settings.windowSize.x); - SDL_SetNumberProperty(windowProperties, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, settings.windowSize.y); - - SDL_SetNumberProperty(windowProperties, SDL_PROP_WINDOW_CREATE_X_NUMBER, - settings.isDefault ? SDL_WINDOWPOS_CENTERED : settings.windowPosition.x); - SDL_SetNumberProperty(windowProperties, SDL_PROP_WINDOW_CREATE_Y_NUMBER, - settings.isDefault ? SDL_WINDOWPOS_CENTERED : settings.windowPosition.y); - - SDL_SetBooleanProperty(windowProperties, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true); - SDL_SetBooleanProperty(windowProperties, SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, true); - SDL_SetBooleanProperty(windowProperties, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true); - - window = SDL_CreateWindowWithProperties(windowProperties); - SDL_DestroyProperties(windowProperties); - - if (!window) - { - logger.fatal(std::format("Could not initialize window! {}", SDL_GetError())); - isError = true; - return; - } - - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); - - glContext = SDL_GL_CreateContext(window); - - if (!glContext) - { - logger.fatal(std::format("Could not initialize OpenGL context! {}", SDL_GetError())); - isError = true; - return; - } - - if (!gl_load()) - { - logger.fatal(std::format("Could not initialize OpenGL!")); - isError = true; - return; - } - - logger.info(std::format("Initialized OpenGL {}", (const char*)gl.GetString(GL_VERSION))); - - gl.Enable(GL_BLEND); - gl.BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - gl.LineWidth(2.0f); - gl.Disable(GL_DEPTH_TEST); - gl.Disable(GL_LINE_SMOOTH); - - random_seed_set(); - - IMGUI_CHECKVERSION(); - if (!ImGui::CreateContext()) - { - logger.fatal("Could not initialize Dear ImGui!"); - isError = true; - return; - } - - logger.info("Initialized Dear ImGui"); - - theme_set((Theme)settings.theme); - - ImGui_ImplSDL3_InitForOpenGL(window, glContext); - ImGui_ImplOpenGL3_Init("#version 330"); - - ImGuiIO& io = ImGui::GetIO(); - io.IniFilename = nullptr; - io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; - if (settings.isDetachableWindows) - io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; - io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; - io.KeyRepeatDelay = settings.keyboardRepeatDelay; - io.KeyRepeatRate = settings.keyboardRepeatRate; - ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); - io.ConfigWindowsMoveFromTitleBarOnly = true; - - if (auto imguiData = Settings::imgui_data_load(settings_path()); !imguiData.empty()) - ImGui::LoadIniSettingsFromMemory(imguiData.c_str(), imguiData.size()); - - if (isSocketThread) - { - isSocketRunning = true; - socketThread = std::thread([this]() { - while (isSocketRunning) - { - try - { - auto client = socket.accept(); - if (!client.is_valid()) - { - if (!isSocketRunning) - break; - continue; - } - - auto paths = socket_paths_receive(client); - for (auto& path : paths) - { - if (path.empty()) - continue; - SDL_Event event = {}; - event.type = SDL_EVENT_USER; - event.user.code = 0; - event.user.data1 = SDL_strdup(path.c_str()); - event.user.data2 = nullptr; - event.user.windowID = 0; - SDL_PushEvent(&event); - } - } - catch (const std::exception& ex) - { - logger.error(std::format("Socket thread error: {}", ex.what())); - } - catch (...) - { - logger.error("Socket thread error: unknown exception"); - } - } - }); - } -} - -Loader::~Loader() -{ - if (isSocketThread) - { - isSocketRunning = false; - - if (socket.is_valid()) - { - Socket wakeSocket; - if (wakeSocket.open(CLIENT) && wakeSocket.connect({SOCKET_ADDRESS, SOCKET_PORT})) - socket_paths_send(wakeSocket, {}); - } - - socket.close(); - if (socketThread.joinable()) - socketThread.join(); - } - - if (ImGui::GetCurrentContext()) - { - settings.save(settings_path(), ImGui::SaveIniSettingsToMemory(nullptr)); - texture_garbage_collect(); - - ImGui_ImplSDL3_Shutdown(); - ImGui_ImplOpenGL3_Shutdown(); - ImGui::DestroyContext(); - } - - - if (SDL_WasInit(0)) - { - SDL_GL_DestroyContext(glContext); - SDL_DestroyWindow(window); - SDL_Quit(); - } -} diff --git a/src/loader.h b/src/loader.h deleted file mode 100644 index e881b15..0000000 --- a/src/loader.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include - -#include "settings.h" -#include "socket.h" - -class Loader -{ - std::filesystem::path settings_path(); - -public: - Socket socket = {}; - std::thread socketThread; - std::atomic_bool isSocketRunning = {}; - SDL_Window* window = nullptr; - SDL_GLContext glContext = {}; - Settings settings; - std::vector arguments; - bool isError = false; - bool isSocketThread = false; - - Loader(int, const char**); - ~Loader(); -}; diff --git a/src/main.cpp b/src/main.cpp index ebc9301..69daa3b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,68 +1,412 @@ +#include +#include +#include +#include +#include +#include +#include + #include "cli.h" -#include "loader.h" +#include "gl.h" +#include "instance.h" +#include "localization.h" #include "log.h" +#include "math_util.h" +#include "path.h" #include "sdl.h" -#include "state.h" +#include "snapshots.h" +#include "texture.h" +#include "ui/dockspace.h" +#include "ui/shortcut.h" +#include "ui/theme.h" +#include "ui/toast.h" #ifdef _WIN32 -#define SDL_MAIN_HANDLED -#include -#include -#include -#include -#include #include #endif -#ifdef _WIN32 -struct CommandLineArguments +constexpr auto UPDATE_INTERVAL_MS = 1000 / 120; +constexpr auto TICK_DELTA_MAX_MS = 250; +constexpr auto WINDOW_4K_SIZE = glm::ivec2(3840, 2160); +constexpr auto UI_SCALE_4K_DEFAULT = 150.0f; +constexpr auto WINDOW_DEFAULT_SIZE_MULTIPLIER = 0.90f; +constexpr auto GL_VERSION_MAJOR = 3; +constexpr auto GL_VERSION_MINOR = 3; +constexpr auto GLSL_VERSION = "#version 330"; +constexpr auto LINE_WIDTH = 2.0f; +constexpr ImGuiKey DOCUMENT_KEYS[] = {ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, + ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, ImGuiKey_0}; + +// The window, its OpenGL context, the settings it opened with, and the main loop's clocks. +struct App { - std::vector strings; - std::vector pointers; + SDL_Window* window = nullptr; + SDL_GLContext context = nullptr; + Settings settings; + std::vector spritesheetDropPaths; + std::vector soundDropPaths; + Uint64 previousTick = 0; + Uint64 previousUpdate = 0; + double tickAccumulatorMs = 0; + bool isQuit = false; + bool isQuitting = false; + bool isRecording = false; }; -std::string wstring_utf8_get(std::wstring_view value) +// Everything the window shows. Made once ImGui is up, which its fonts and icons need. +struct Editor { - if (value.empty()) - return {}; - auto size = WideCharToMultiByte(CP_UTF8, 0, value.data(), (int)value.size(), nullptr, 0, nullptr, nullptr); - if (size <= 0) - return {}; + Manager manager; + Resources resources; + Dialog dialog; + Clipboard clipboard; + Taskbar taskbar; + Documents documents; + Dockspace dockspace; +}; - std::string utf8((std::size_t)size, '\0'); - WideCharToMultiByte(CP_UTF8, 0, value.data(), (int)value.size(), utf8.data(), size, nullptr, nullptr); - return utf8; +static std::filesystem::path settings_path_get() +{ + return preferences_directory_get() / "settings.ini"; } -CommandLineArguments command_line_arguments_get() +// A first run's window covers most of the primary display, with a larger interface on 4K ones. +static void window_size_default(Settings& settings) { - int count = 0; - auto wideArguments = CommandLineToArgvW(GetCommandLineW(), &count); - if (!wideArguments) - return {}; - if (count <= 0) + auto mode = SDL_GetCurrentDisplayMode(SDL_GetPrimaryDisplay()); + if (!mode) { - LocalFree(wideArguments); - return {}; + logger.warning(std::format("Failed to query primary display mode: {}", SDL_GetError())); + return; + } + if (mode->w >= WINDOW_4K_SIZE.x || mode->h >= WINDOW_4K_SIZE.y) + settings.uiScale = UI_SCALE_4K_DEFAULT; + settings.windowSize.x = mode->w * WINDOW_DEFAULT_SIZE_MULTIPLIER; + settings.windowSize.y = mode->h * WINDOW_DEFAULT_SIZE_MULTIPLIER; +} + +static bool window_open(App& app) +{ + auto& settings = app.settings; + settings = Settings(settings_path_get()); + SnapshotStack::max_size_set(settings.fileSnapshotStackSize); + localize.language = (Language)settings.language; + + if (!SDL_Init(SDL_INIT_VIDEO)) + { + logger.fatal(std::format("Could not initialize SDL! {}", SDL_GetError())); + return false; + } + if (settings.isDefault) + window_size_default(settings); + + auto properties = SDL_CreateProperties(); + SDL_SetStringProperty(properties, SDL_PROP_WINDOW_CREATE_TITLE_STRING, "Anm2Ed"); + SDL_SetNumberProperty(properties, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, settings.windowSize.x); + SDL_SetNumberProperty(properties, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, settings.windowSize.y); + SDL_SetNumberProperty(properties, SDL_PROP_WINDOW_CREATE_X_NUMBER, + settings.isDefault ? SDL_WINDOWPOS_CENTERED : settings.windowPosition.x); + SDL_SetNumberProperty(properties, SDL_PROP_WINDOW_CREATE_Y_NUMBER, + settings.isDefault ? SDL_WINDOWPOS_CENTERED : settings.windowPosition.y); + SDL_SetBooleanProperty(properties, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true); + SDL_SetBooleanProperty(properties, SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, true); + SDL_SetBooleanProperty(properties, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true); + app.window = SDL_CreateWindowWithProperties(properties); + SDL_DestroyProperties(properties); + if (!app.window) + { + logger.fatal(std::format("Could not initialize window! {}", SDL_GetError())); + return false; } - CommandLineArguments arguments = {}; - arguments.strings.reserve((std::size_t)count); - for (int i = 0; i < count; ++i) - arguments.strings.push_back(wstring_utf8_get(wideArguments[i])); - LocalFree(wideArguments); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, GL_VERSION_MAJOR); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, GL_VERSION_MINOR); + app.context = SDL_GL_CreateContext(app.window); + if (!app.context || !gl_load()) + { + logger.fatal(std::format("Could not initialize OpenGL! {}", SDL_GetError())); + return false; + } + logger.info(std::format("Initialized OpenGL {}", (const char*)gl.GetString(GL_VERSION))); + gl.Enable(GL_BLEND); + gl.BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + gl.LineWidth(LINE_WIDTH); + gl.Disable(GL_DEPTH_TEST); + gl.Disable(GL_LINE_SMOOTH); + SDL_GL_SetSwapInterval(settings.isVsync); + random_seed_set(); - arguments.pointers.reserve(arguments.strings.size()); - for (auto& argument : arguments.strings) - arguments.pointers.push_back(argument.c_str()); + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + theme_set((Theme)settings.theme); + ImGui_ImplSDL3_InitForOpenGL(app.window, app.context); + ImGui_ImplOpenGL3_Init(GLSL_VERSION); - return arguments; + auto& io = ImGui::GetIO(); + io.IniFilename = nullptr; + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableKeyboard; + if (settings.isDetachableWindows) + io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; + io.KeyRepeatDelay = settings.keyboardRepeatDelay; + io.KeyRepeatRate = settings.keyboardRepeatRate; + io.ConfigWindowsMoveFromTitleBarOnly = true; + ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); + if (auto imguiData = Settings::imgui_data_load(settings_path_get()); !imguiData.empty()) + ImGui::LoadIniSettingsFromMemory(imguiData.c_str(), imguiData.size()); + return true; } -#endif -static int application_run(int argc, const char** argv) +static void window_close(App& app) { - if (is_cli(argc, argv)) + if (ImGui::GetCurrentContext()) + { + app.settings.save(settings_path_get(), ImGui::SaveIniSettingsToMemory(nullptr)); + texture_garbage_collect(); + ImGui_ImplSDL3_Shutdown(); + ImGui_ImplOpenGL3_Shutdown(); + ImGui::DestroyContext(); + } + SDL_GL_DestroyContext(app.context); + SDL_DestroyWindow(app.window); + SDL_Quit(); +} + +static void file_drop(App& app, Editor& editor, const std::filesystem::path& path) +{ + auto& manager = editor.manager; + if (is_path_extension(path, "anm2")) + { + if (manager.documents.empty()) + manager.open(path); + else + { + if (std::ranges::find(manager.anm2DragDropPaths, path) == manager.anm2DragDropPaths.end()) + manager.anm2DragDropPaths.push_back(path); + manager.isAnm2DragDrop = true; + } + SDL_FlashWindow(app.window, SDL_FLASH_UNTIL_FOCUSED); + } + else if (is_path_extension(path, PNG_EXTENSION) || is_path_extension(path, SVG_EXTENSION)) + app.spritesheetDropPaths.push_back(path); + else if (is_path_extension(path, "wav") || is_path_extension(path, "ogg")) + app.soundDropPaths.push_back(path); +} + +// Dropped spritesheets and sounds go into the current document, together. +static void file_drop_complete(App& app, Editor& editor) +{ + auto& manager = editor.manager; + if (manager.get()) + { + if (auto paths = app.spritesheetDropPaths; !paths.empty()) + manager.command_push( + {manager.selected, [paths](Manager&, Document& document) { document.spritesheets_add(paths); }}); + if (auto paths = app.soundDropPaths; !paths.empty()) + manager.command_push( + {manager.selected, [paths](Manager&, Document& document) { document.sounds_add(paths); }}); + } + else + { + if (!app.spritesheetDropPaths.empty()) + toast_log(Level::WARNING, TOAST_ADD_SPRITESHEET_FAILED); + if (!app.soundDropPaths.empty()) + toast_log(Level::WARNING, TOAST_ADD_SOUND_FAILED); + } + app.spritesheetDropPaths.clear(); + app.soundDropPaths.clear(); +} + +static void events_poll(App& app, Editor& editor) +{ + SDL_Event event = {}; + while (SDL_PollEvent(&event)) + { + ImGui_ImplSDL3_ProcessEvent(&event); + switch (event.type) + { + case SDL_EVENT_DROP_BEGIN: + app.spritesheetDropPaths.clear(); + app.soundDropPaths.clear(); + break; + case SDL_EVENT_DROP_FILE: + if (event.drop.data && *event.drop.data) + file_drop(app, editor, path_from_utf8(event.drop.data)); + break; + case SDL_EVENT_DROP_COMPLETE: + file_drop_complete(app, editor); + break; + // A path handed over by another instance (see instance.h). + case SDL_EVENT_USER: + { + auto path = path_from_utf8((const char*)event.user.data1); + SDL_free(event.user.data1); + if (is_path_extension(path, "anm2")) + { + editor.manager.open(path); + SDL_FlashWindow(app.window, SDL_FLASH_UNTIL_FOCUSED); + } + break; + } + case SDL_EVENT_QUIT: + app.isQuitting = true; + break; + // With detached windows open, closing the main window doesn't end the event loop by itself. + case SDL_EVENT_WINDOW_CLOSE_REQUESTED: + if (event.window.windowID == SDL_GetWindowID(app.window)) + app.isQuitting = true; + break; + default: + break; + } + } +} + +// Ctrl+1 to Ctrl+0 switch to the first ten documents. +static void document_shortcuts_update(Manager& manager) +{ + if (ImGui::GetTopMostPopupModal()) + return; + for (int i = 0; i < (int)std::size(DOCUMENT_KEYS) && i < (int)manager.documents.size(); ++i) + if (ImGui::Shortcut(ImGuiMod_Ctrl | DOCUMENT_KEYS[i], ImGuiInputFlags_RouteGlobal)) + { + manager.set(i); + manager.pendingSelected = i; + return; + } +} + +static void ui_scale_update(App& app, Editor& editor) +{ + if (editor.dockspace.is_canvas_focused_get()) + return; + auto& settings = app.settings; + auto delta = 0.0f; + if (shortcut(editor.manager.chords[SHORTCUT_ZOOM_IN], SCOPE_GLOBAL)) + delta += UI_SCALE_STEP; + if (shortcut(editor.manager.chords[SHORTCUT_ZOOM_OUT], SCOPE_GLOBAL)) + delta -= UI_SCALE_STEP; + if (delta == 0.0f) + return; + settings.uiScale = std::clamp(settings.uiScale + delta, UI_SCALE_MIN, UI_SCALE_MAX); + ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); +} + +static void frame_update(App& app, Editor& editor) +{ + auto& settings = app.settings; + events_poll(app, editor); + + ImGui_ImplSDL3_NewFrame(); + ImGui_ImplOpenGL3_NewFrame(); + ImGui::NewFrame(); + + editor.documents.pending_document_order_apply(editor.manager); + document_shortcuts_update(editor.manager); + editor.taskbar.update(editor.manager, settings, editor.resources, editor.dialog, app.isQuitting); + editor.documents.update(editor.taskbar, editor.manager, settings, editor.resources, app.isQuitting); + editor.dockspace.update(editor.taskbar, editor.documents, editor.manager, settings, editor.resources, + editor.dialog, editor.clipboard); + ui_scale_update(app, editor); + toasts.update(); + editor.manager.commands_run(); + + SDL_GetWindowSize(app.window, &settings.windowSize.x, &settings.windowSize.y); + SDL_GetWindowPosition(app.window, &settings.windowPosition.x, &settings.windowPosition.y); + if (app.isQuitting && editor.manager.documents.empty()) + app.isQuit = true; +} + +static void frame_render(App& app) +{ + gl.Viewport(0, 0, app.settings.windowSize.x, app.settings.windowSize.y); + gl.Clear(GL_COLOR_BUFFER_BIT); + ImGui::Render(); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + + // Windows dragged out of the main window are drawn into their own OS windows (and GL contexts). + if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + auto context = SDL_GL_GetCurrentContext(); + ImGui::UpdatePlatformWindows(); + ImGui::RenderPlatformWindowsDefault(); + SDL_GL_MakeCurrent(app.window, context); + } + + SDL_GL_SwapWindow(app.window); + texture_garbage_collect(); + SDL_GL_SetSwapInterval(app.settings.isVsync); +} + +// Draws at most every UPDATE_INTERVAL_MS, and ticks playback at the playback tick rate in between. +static void loop_step(App& app, Editor& editor) +{ + auto now = SDL_GetTicks(); + auto tickIntervalMs = 1000.0 / std::max(app.settings.playbackTickRate, 1); + + // Recording starting or stopping drops the backlog. + if (editor.manager.isRecording != app.isRecording) + { + app.tickAccumulatorMs = 0; + app.previousTick = now; + app.isRecording = editor.manager.isRecording; + } + if (app.previousTick == 0) + app.previousTick = now; + app.tickAccumulatorMs += (double)std::min(now - app.previousTick, TICK_DELTA_MAX_MS); + app.previousTick = now; + + if (now - app.previousUpdate >= UPDATE_INTERVAL_MS) + { + frame_update(app, editor); + frame_render(app); + app.previousUpdate = now; + } + + if (app.tickAccumulatorMs >= tickIntervalMs) + { + editor.dockspace.tick(editor.manager, app.settings, (float)(tickIntervalMs / 1000.0)); + app.tickAccumulatorMs -= tickIntervalMs; + } + + SDL_Delay(1); +} + +static int editor_run(int argc, char* argv[]) +{ + std::vector arguments(argv + 1, argv + argc); + switch (instance_start(arguments)) + { + case INSTANCE_FORWARDED: + logger.info("Handed the arguments to the running instance."); + return EXIT_SUCCESS; + case INSTANCE_ALONE: + logger.warning("Another program holds the single-instance port. Running without it."); + break; + default: + break; + } + + App app; + auto isOpen = window_open(app); + if (isOpen) + { + Editor editor; + editor.dialog = Dialog(app.window); + for (auto& argument : arguments) + editor.manager.open(path_from_utf8(argument)); + editor.manager.settings_apply(app.settings); + while (!app.isQuit) + loop_step(app, editor); + } + instance_stop(); + window_close(app); + return isOpen ? EXIT_SUCCESS : EXIT_FAILURE; +} + +int main(int argc, char* argv[]) +{ + if (is_cli(argc, (const char**)argv)) { #ifdef _WIN32 // A GUI-subsystem build has no console of its own. Print to the one it was started from. @@ -72,39 +416,9 @@ static int application_run(int argc, const char** argv) freopen("CONOUT$", "w", stderr); } #endif - return cli_run(argc, argv); + return cli_run(argc, (const char**)argv); } logger.session_open(preferences_directory_get()); - return log_exceptions([&]() { - Loader loader(argc, argv); - - if (loader.isError) - return EXIT_FAILURE; - - State state(loader.window, loader.settings, loader.arguments); - - while (!state.isQuit) - state.loop(loader.window, loader.settings); - - return EXIT_SUCCESS; - }); + return log_exceptions([&] { return editor_run(argc, argv); }); } - -int main(int argc, const char** argv) -{ -#ifdef _WIN32 - auto arguments = command_line_arguments_get(); - if (!arguments.pointers.empty()) - return application_run((int)arguments.pointers.size(), arguments.pointers.data()); -#endif - return application_run(argc, argv); -} - -#ifdef _WIN32 -int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int) -{ - auto arguments = command_line_arguments_get(); - return application_run((int)arguments.pointers.size(), arguments.pointers.data()); -} -#endif diff --git a/src/socket.cpp b/src/socket.cpp deleted file mode 100644 index 72b5bed..0000000 --- a/src/socket.cpp +++ /dev/null @@ -1,275 +0,0 @@ -#include "socket.h" - -#include -#include - -#ifdef _WIN32 -struct WSAInitializer -{ - WSAInitializer() - { - WSADATA data = {}; - WSAStartup(MAKEWORD(2, 2), &data); - } - ~WSAInitializer() - { - WSACleanup(); - } -}; - -WSAInitializer initializer = {}; -#endif - -static int socket_last_error() -{ -#ifdef _WIN32 - return WSAGetLastError(); -#else - return errno; -#endif -} - -Socket::Socket() : handle(SOCKET_INVALID), role(CLIENT), lastError(0) -{} - -Socket::Socket(Socket&& other) noexcept : handle(other.handle), role(other.role), lastError(other.lastError) -{ - other.handle = SOCKET_INVALID; - other.lastError = 0; -} - -Socket& Socket::operator=(Socket&& other) noexcept -{ - if (this != &other) - { - close(); - handle = other.handle; - role = other.role; - other.handle = SOCKET_INVALID; - lastError = other.lastError; - other.lastError = 0; - } - - return *this; -} - -Socket::~Socket() -{ - close(); -} - -bool Socket::open(SocketRole newRole) -{ - close(); - role = newRole; - - handle = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - - if (!is_valid()) - { - lastError = socket_last_error(); - return false; - } - - if (role == SERVER) - { -#ifdef _WIN32 - BOOL opt = TRUE; - if (::setsockopt(handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast(&opt), sizeof(opt)) != - 0) - { - lastError = socket_last_error(); - close(); - return false; - } -#else - int opt = 1; - if (::setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&opt), sizeof(opt)) != 0) - { - lastError = socket_last_error(); - close(); - return false; - } -#endif - } - - lastError = 0; - return true; -} - -bool Socket::bind(const SocketAddress& address) -{ - if (!is_valid()) - { - lastError = EINVAL; - return false; - } - - sockaddr_in addr = {}; - addr.sin_family = AF_INET; - addr.sin_port = htons(address.port); - - if (address.host.empty()) - addr.sin_addr.s_addr = htonl(INADDR_ANY); - else if (::inet_pton(AF_INET, address.host.c_str(), &addr.sin_addr) <= 0) - { - lastError = socket_last_error(); - return false; - } - - if (::bind(handle, reinterpret_cast(&addr), sizeof(addr)) == 0) - { - lastError = 0; - return true; - } - - lastError = socket_last_error(); - return false; -} - -bool Socket::listen() -{ - if (!is_valid()) - { - lastError = EINVAL; - return false; - } - if (::listen(handle, SOMAXCONN) == 0) - { - lastError = 0; - return true; - } - - lastError = socket_last_error(); - return false; -} - -Socket Socket::accept() -{ - Socket client = {}; - if (!is_valid()) - return client; - - auto accepted = ::accept(handle, nullptr, nullptr); - if (accepted == SOCKET_INVALID) - { - lastError = socket_last_error(); - return client; - } - - client.close(); - client.handle = accepted; - client.role = CLIENT; - lastError = 0; - return client; -} - -bool Socket::connect(const SocketAddress& address) -{ - if (!is_valid()) - { - lastError = EINVAL; - return false; - } - - sockaddr_in addr = {}; - addr.sin_family = AF_INET; - addr.sin_port = htons(address.port); - - if (::inet_pton(AF_INET, address.host.c_str(), &addr.sin_addr) <= 0) - { - lastError = socket_last_error(); - return false; - } - - if (::connect(handle, reinterpret_cast(&addr), sizeof(addr)) == 0) - { - lastError = 0; - return true; - } - - lastError = socket_last_error(); - return false; -} - -bool Socket::send(const void* data, size_t size) -{ - if (!is_valid() || !data || size == 0) - { - lastError = EINVAL; - return false; - } - - auto bytes = reinterpret_cast(data); - size_t totalSent = 0; - - while (totalSent < size) - { - auto chunkSize = static_cast(std::min(size - totalSent, static_cast(INT_MAX))); -#ifdef MSG_NOSIGNAL - auto sent = ::send(handle, bytes + totalSent, chunkSize, MSG_NOSIGNAL); -#else - auto sent = ::send(handle, bytes + totalSent, chunkSize, 0); -#endif - if (sent <= 0) - { - lastError = socket_last_error(); - return false; - } - totalSent += static_cast(sent); - } - - lastError = 0; - return true; -} - -bool Socket::receive(void* buffer, size_t size) -{ - if (!is_valid() || !buffer || size == 0) - { - lastError = EINVAL; - return false; - } - - auto* bytes = reinterpret_cast(buffer); - size_t totalReceived = 0; - - while (totalReceived < size) - { - auto chunkSize = static_cast(std::min(size - totalReceived, static_cast(INT_MAX))); - auto received = ::recv(handle, bytes + totalReceived, chunkSize, 0); - if (received <= 0) - { - lastError = socket_last_error(); - return false; - } - totalReceived += static_cast(received); - } - - lastError = 0; - return true; -} - -void Socket::close() -{ - if (!is_valid()) - return; - -#ifdef _WIN32 - ::closesocket(handle); -#else - ::close(handle); -#endif - handle = SOCKET_INVALID; - lastError = 0; -} - -bool Socket::is_valid() const -{ - return handle != SOCKET_INVALID; -} - -int Socket::last_error() const -{ - return lastError; -} diff --git a/src/socket.h b/src/socket.h deleted file mode 100644 index 70243bd..0000000 --- a/src/socket.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once - -#include -#include - -#ifdef _WIN32 -#include -#include -using socket_handle = SOCKET; -constexpr socket_handle SOCKET_INVALID = INVALID_SOCKET; -#else -#include -#include -#include -#include -using socket_handle = int; -constexpr socket_handle SOCKET_INVALID = -1; -#endif - -enum SocketRole -{ - SERVER, - CLIENT -}; - -struct SocketAddress -{ - std::string host; - unsigned short port = {}; -}; - -class Socket -{ -private: - socket_handle handle; - SocketRole role = {}; - int lastError = 0; - -public: - Socket(); - ~Socket(); - - Socket(const Socket&) = delete; - Socket& operator=(const Socket&) = delete; - Socket(Socket&& other) noexcept; - Socket& operator=(Socket&& other) noexcept; - - bool open(SocketRole role); - bool bind(const SocketAddress&); - bool listen(); - Socket accept(); - bool connect(const SocketAddress&); - - bool send(const void*, size_t); - bool receive(void*, size_t); - - void close(); - bool is_valid() const; - int last_error() const; -}; diff --git a/src/state.cpp b/src/state.cpp deleted file mode 100644 index 818e75a..0000000 --- a/src/state.cpp +++ /dev/null @@ -1,269 +0,0 @@ -#include "state.h" - -#include - -#include - -#include -#include - -#include "log.h" -#include "math_util.h" -#include "path.h" -#include "localization.h" -#include "texture.h" -#include "ui/toast.h" -#include "ui/shortcut.h" - -constexpr auto UPDATE_RATE = 120; -constexpr auto UPDATE_INTERVAL = (1000 / UPDATE_RATE); - -State::State(SDL_Window*& window, Settings& settings, std::vector& arguments) -{ - dialog = Dialog(window); - - for (auto& argument : arguments) - manager.open(path_from_utf8(argument)); - - manager.settings_apply(settings); -} - -void State::tick(Settings& settings, float deltaSeconds) -{ - dockspace.tick(manager, settings, deltaSeconds); -} - -void State::update(SDL_Window*& window, Settings& settings) -{ - /* - ImGui_ImplSDL3_NewFrame(); - ImGui_ImplOpenGL3_NewFrame(); - ImGui::NewFrame(); - - SDL_GetWindowSize(window, &settings.windowSize.x, &settings.windowSize.y); - SDL_GetWindowPosition(window, &settings.windowPosition.x, &settings.windowPosition.y); - - SDL_Event event = {}; - - while (SDL_PollEvent(&event)) - { - switch (event.type) - { - case SDL_EVENT_QUIT: - isQuit = true; - default: - break; - } - } - - dockspace.update(taskbar, documents, manager, settings, resources, dialog, clipboard); - */ - - SDL_Event event = {}; - - while (SDL_PollEvent(&event)) - { - ImGui_ImplSDL3_ProcessEvent(&event); - switch (event.type) - { - case SDL_EVENT_DROP_BEGIN: - spritesheetDropPaths.clear(); - soundDropPaths.clear(); - break; - case SDL_EVENT_DROP_FILE: - { - std::string droppedFile = event.drop.data ? event.drop.data : ""; - if (droppedFile.empty()) - break; - auto droppedPath = path_from_utf8(droppedFile); - if (is_path_extension(droppedPath, "anm2")) - { - if (manager.documents.empty()) - manager.open(droppedPath); - else - { - if (std::find(manager.anm2DragDropPaths.begin(), manager.anm2DragDropPaths.end(), - droppedPath) == manager.anm2DragDropPaths.end()) - manager.anm2DragDropPaths.push_back(droppedPath); - manager.isAnm2DragDrop = true; - } - SDL_FlashWindow(window, SDL_FLASH_UNTIL_FOCUSED); - } - else if (is_path_extension(droppedPath, PNG_EXTENSION) || is_path_extension(droppedPath, SVG_EXTENSION)) - { - spritesheetDropPaths.push_back(droppedPath); - } - else if (is_path_extension(droppedPath, "wav") || is_path_extension(droppedPath, "ogg")) - { - soundDropPaths.push_back(droppedPath); - } - break; - } - case SDL_EVENT_DROP_COMPLETE: - { - if (auto document = manager.get(); document) - { - if (!spritesheetDropPaths.empty()) - { - auto paths = spritesheetDropPaths; - manager.command_push({manager.selected, [paths](Manager&, Document& document) { - document.spritesheets_add(paths); - }}); - } - if (!soundDropPaths.empty()) - { - auto paths = soundDropPaths; - manager.command_push( - {manager.selected, [paths](Manager&, Document& document) { document.sounds_add(paths); }}); - } - } - else - { - if (!spritesheetDropPaths.empty()) - toast_log(Level::WARNING, TOAST_ADD_SPRITESHEET_FAILED); - if (!soundDropPaths.empty()) - toast_log(Level::WARNING, TOAST_ADD_SOUND_FAILED); - } - spritesheetDropPaths.clear(); - soundDropPaths.clear(); - break; - } - case SDL_EVENT_USER: // Opening files - { - std::string droppedFile = event.user.data1 ? static_cast(event.user.data1) : ""; - if (event.user.data1) - SDL_free(event.user.data1); - if (droppedFile.empty()) - break; - auto droppedPath = path_from_utf8(droppedFile); - if (is_path_extension(droppedPath, "anm2")) - { - manager.open(droppedPath); - SDL_FlashWindow(window, SDL_FLASH_UNTIL_FOCUSED); - } - break; - } - case SDL_EVENT_QUIT: - isQuitting = true; - break; - // With detached windows open, closing the main window doesn't end the event loop by itself. - case SDL_EVENT_WINDOW_CLOSE_REQUESTED: - if (event.window.windowID == SDL_GetWindowID(window)) - isQuitting = true; - break; - default: - break; - } - } - - ImGui_ImplSDL3_NewFrame(); - ImGui_ImplOpenGL3_NewFrame(); - ImGui::NewFrame(); - - documents.pending_document_order_apply(manager); - - if (ImGui::GetTopMostPopupModal() == nullptr) - { - constexpr ImGuiKey DOCUMENT_SHORTCUT_KEYS[] = {ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, - ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, ImGuiKey_0}; - for (int i = 0; i < (int)(sizeof(DOCUMENT_SHORTCUT_KEYS) / sizeof(DOCUMENT_SHORTCUT_KEYS[0])); ++i) - { - if (i >= (int)manager.documents.size()) - break; - if (ImGui::Shortcut(ImGuiMod_Ctrl | DOCUMENT_SHORTCUT_KEYS[i], ImGuiInputFlags_RouteGlobal)) - { - manager.set(i); - manager.pendingSelected = i; - break; - } - } - } - - taskbar.update(manager, settings, resources, dialog, isQuitting); - documents.update(taskbar, manager, settings, resources, isQuitting); - dockspace.update(taskbar, documents, manager, settings, resources, dialog, clipboard); - - if (!dockspace.is_canvas_focused_get()) - { - float uiScaleDelta = 0; - if (shortcut(manager.chords[SHORTCUT_ZOOM_IN], SCOPE_GLOBAL)) - uiScaleDelta += UI_SCALE_STEP; - if (shortcut(manager.chords[SHORTCUT_ZOOM_OUT], SCOPE_GLOBAL)) - uiScaleDelta -= UI_SCALE_STEP; - if (uiScaleDelta != 0.0f) - { - settings.uiScale = std::clamp(settings.uiScale + uiScaleDelta, UI_SCALE_MIN, UI_SCALE_MAX); - ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); - } - } - - toasts.update(); - manager.commands_run(); - - SDL_GetWindowSize(window, &settings.windowSize.x, &settings.windowSize.y); - SDL_GetWindowPosition(window, &settings.windowPosition.x, &settings.windowPosition.y); - - if (isQuitting && manager.documents.empty()) - isQuit = true; -} - -void State::render(SDL_Window*& window, Settings& settings) -{ - gl.Viewport(0, 0, settings.windowSize.x, settings.windowSize.y); - gl.Clear(GL_COLOR_BUFFER_BIT); - - ImGui::Render(); - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - - // Windows dragged out of the main window are drawn into their own OS windows (and GL contexts). - if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) - { - auto glContext = SDL_GL_GetCurrentContext(); - ImGui::UpdatePlatformWindows(); - ImGui::RenderPlatformWindowsDefault(); - SDL_GL_MakeCurrent(window, glContext); - } - - SDL_GL_SwapWindow(window); - texture_garbage_collect(); - SDL_GL_SetSwapInterval(settings.isVsync); -} - -void State::loop(SDL_Window*& window, Settings& settings) -{ - auto currentTick = SDL_GetTicks(); - auto currentUpdate = SDL_GetTicks(); - auto isRecording = manager.isRecording; - auto tickRate = std::max(settings.playbackTickRate, 1); - auto tickIntervalMs = 1000.0 / (double)tickRate; - - if (isRecording != wasRecording) - { - // Drop any accumulated backlog when entering/leaving recording mode. - tickAccumulatorMs = 0.0; - previousTick = currentTick; - wasRecording = isRecording; - } - - if (previousTick == 0) - previousTick = currentTick; - auto tickDeltaMs = currentTick - previousTick; - tickDeltaMs = std::min(tickDeltaMs, 250); - tickAccumulatorMs += (double)tickDeltaMs; - previousTick = currentTick; - - if (currentUpdate - previousUpdate >= UPDATE_INTERVAL) - { - update(window, settings); - render(window, settings); - previousUpdate = currentUpdate; - } - - if (tickAccumulatorMs >= tickIntervalMs) - { - tick(settings, (float)(tickIntervalMs / 1000.0)); - tickAccumulatorMs -= tickIntervalMs; - } - - SDL_Delay(1); -} diff --git a/src/state.h b/src/state.h deleted file mode 100644 index b2cc6a7..0000000 --- a/src/state.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include - -#include -#include - -#include "ui/dockspace.h" - -class State -{ - void tick(Settings&, float); - void update(SDL_Window*&, Settings&); - void render(SDL_Window*&, Settings&); - -public: - bool isQuit = false; - bool isQuitting = false; - Manager manager; - Resources resources; - Dialog dialog; - Clipboard clipboard; - - Taskbar taskbar; - Documents documents; - Dockspace dockspace; - - uint64_t previousTick = 0; - uint64_t previousUpdate = 0; - double tickAccumulatorMs = 0; - bool wasRecording = false; - std::vector spritesheetDropPaths; - std::vector soundDropPaths; - - State(SDL_Window*&, Settings& settings, std::vector&); - - void loop(SDL_Window*&, Settings&); -}; diff --git a/tests/render/render.cpp b/tests/render/render.cpp index 2b71893..bf42df3 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -1,6 +1,7 @@ // Animations drawn by the editor's OpenGL renderer, compared with golden PNGs (ANM2ED_UPDATE_GOLDEN=1 rewrites them). // Every render is also written to ANM2ED_RENDER_DIR (build/renders) so it can be looked at. Skipped without OpenGL. +#include #include #include @@ -13,6 +14,7 @@ #include "embed.h" #include "document.h" #include "image.h" +#include "instance.h" #include "render.h" const std::filesystem::path RENDER_TEST_DIR = std::filesystem::path(ANM2ED_TEST_DIR) / "render"; @@ -364,3 +366,23 @@ TEST_CASE("audio decodes and mixes") CHECK(mix[start - 2] == 0.0f); CHECK(mix[start + 2] == doctest::Approx(0.5f).epsilon(0.05)); } + +// A second editor hands its paths to the first and is told it was heard. Skipped when the port is already taken. +TEST_CASE("a second instance hands its paths to the first") +{ + if (!SDL_Init(SDL_INIT_EVENTS)) + return; + if (instance_start({}) != INSTANCE_FIRST) + return; + CHECK(instance_start({"a.anm2", "b.anm2"}) == INSTANCE_FORWARDED); + std::vector paths; + SDL_Event event = {}; + for (int attempt = 0; attempt < 100 && paths.size() < 2; ++attempt) + if (SDL_WaitEventTimeout(&event, 10) && event.type == SDL_EVENT_USER) + { + paths.emplace_back((const char*)event.user.data1); + SDL_free(event.user.data1); + } + instance_stop(); + CHECK(paths == std::vector{"a.anm2", "b.anm2"}); +}